Reputation: 1048
I'm trying to separate a long strong of text between two UILabels in order to wrap around an image. I've re-used and adapted some code left behind by a previous developer on this project which is below...
The String (sequential number words, 1 to 20):
NSString *sampleString = @"One two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty. One two three four five six seven eight nine ten. Eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty.";
The spliting method...
-(void)seperateTextIntoLabels:(NSString*) text
{
// Create array of words from our string
NSArray *words = [text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];
//Data storage for loop
NSMutableString *text1 = [[NSMutableString alloc] init];
NSMutableString *text2 = [[NSMutableString alloc] init];
for(NSString *word in words)
{
CGSize ss1 = [[NSString stringWithFormat:@"%@ %@",text1,word] sizeWithFont:descriptionLabel.font constrainedToSize:CGSizeMake(descriptionLabel.frame.size.width, 9999) lineBreakMode:descriptionLabel.lineBreakMode];
if(ss1.height > descriptionLabel.frame.size.height || ss1.width > descriptionLabel.frame.size.width)
{
if( [text2 length]>0)
{
[text2 appendString: @" "];
}
[text2 appendString: word];
}
else {
if( [text1 length]>0)
{
[text1 appendString: @" "];
}
[text1 appendString:word];
}
}
descriptionLabel.text = text1;
descriptionLabelTwo.text = text2;
[descriptionLabel sizeToFit];
[descriptionLabelTwo sizeToFit];
}
It works more-or-less as I'd expect it to, except it's getting confused at the point where the switch happens.
Notice the last word in label 1 'One' which is misplaced. This word is also missing from mid-way-through the second label. Other than this issue it seems to work ok otherwise.
Any ideas on what's happening here?
Are there any alternative solutions for this? Please note that I'd rather not use a UIWebView (mostly because of the delay in on-screen rendering).
Upvotes: 2
Views: 976
Reputation: 7573
Okey here is your problem.
You are checking for every word in your String if it fits into the first label, then if it doesn't fit. It goes into the second. Up until "twelve" it all fits into the first label. But then you want the rest of the strings to fall into the second label, right?
Well in your check, even after you made the split to the second label, you keep checking if every word fits into the first label too. "One" is the first word that still fits in the first label and thus places it there, and continues with placing the other words in the second label.
To fix this "weird" splitting issue you could make yourself a boolean that when you made the split into the second label turns to "YES" (or true w/e you like) and make sure you check if that boolean is turned on as well as checking for the sizes.
I hope this all makes sense to you now.
Good luck.
Upvotes: 2