iOS >> UILabel: How to Create Lines Separator Relating to Words Count
I use a UILabel that is defined in IB as including 2 lines
The text itself is coming from the cod开发者_StackOverflowe:
[self.myUILabel setText:[someDictionaryThatHoldsNSStrings objectForKey:someDictionaryKey]];
There are always 4 words in the string; I want to make sure that in any case there will always be 2 words in the first line and 2 words in the second line but using Word Wrap doesn't do the trick since the length of the word is deferent depending on the strings.
How do I define that the UILabel will always hold 2 words in the first line and 2 words in the second line?
Instead of trying to find the length of the words and finding the size for the words, you can add a newline(\n
) character after the two words and display it in the label without altering the label's size or lineBreakMode.
- (NSString *)formatSentenceIntoTwoLines:(NSString *)sentence {
sentence = [sentence stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSArray *words = [sentence componentsSeparatedByString:@" "];
NSString *word_1 = [words objectAtIndex:0];
NSString *word_2 = [words objectAtIndex:1];
NSString *word_3 = [words objectAtIndex:2];
NSString *word_4 = [words objectAtIndex:3];
NSString *firstTwoWords = [word_1 stringByAppendingFormat:@" %@", word_2];
NSString *lastTwoWords = [word_3 stringByAppendingFormat:@" %@", word_4];
NSString *formattedSentence = [firstTwoWords stringByAppendingFormat:@"\n%@", lastTwoWords];
return formattedSentence;
}
Use the above method to format the string. The code seems too big. I write it in this way just to make it understandable. You can still simplify it as you want.
And make sure the numberOfLines of label set to 2
(label will show only two lines) or 0
(for dynamic number of lines).
label.numberOfLines = 2; // 0 if there is going to be dynamic number of lines
Try putting a line break between the second and third word. Make sure to checkout this post because sometimes there are some problems getting the label to recognize the line break based on the source of the string.
Another simple option would be to use two UILabels, one for the first two words and a second placed underneath it for the next two words.
I think this post could help you, for breaking lines : How to add line break for UILabel?
And this one could help you if you want to count words (maybe in case your string is obtained dynamically) : What is the most efficient way to count number of word in NSString without using regex?
You should set the numberOfLines property of your UILabel to 0. (unlimited number of lines). After that, I think you should count the words in your NSString (with NSScanner or this method), and add a "\n" character dynamically after the second word.
Hope this helps, Jérémy.
精彩评论