Reputation: 2217
I have a multiline UILabel
with the text "I would like to ride a boat in indian ocean". In iPhone 5 the UILabel
displays the text "ocean" in the second line because of width size.
What I want is If text in UILabel
appears in two lines, then the text "indian ocean" should display in second line or in case of sufficient width available, all text should appear in one line.
Any ideas how to achieve this.
Upvotes: 2
Views: 1069
Reputation: 1
Here is an UILabel extension for showing consecutive text components in same line.
https://github.com/Umair-Bhatti/ConsecutiveComponents
Just add the file and following line of code
label.addConsectiveComponents(["indian ocean"])
It will show "indian ocean" always in one line i.e. if there is space in current line it will be shown there otherwise in next line.
Upvotes: 0
Reputation: 743
Its a work around. But this suits your requirement with no need of determining the device on which app runs. Generally UILabel
wraps the words around whitespaces
. So probably you should make indian ocean
a single word, but still it should be displayed as two separate words.
let string = "<font size = 5 face = Avenir Next>I would like to ride a boat in<font color = white>_</font>indian ocean</font>"
let attributedString = try? NSAttributedString(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil)
label.attributedText = attributedString
You can specify the required font size, family and set the color of _
to the backgroundColor
of UILabel
.
Upvotes: 1
Reputation: 2520
No need to use device detection...using one trick you can solve this problem "if label displays the text in two lines, then the text "indian ocean" will display second line or it will display in first line."
Steps to follow :
UILabel
's text type from plain to attribute in attribute inspector.That's it.
Upvotes: 1
Reputation: 33
label.numberOfLines = 0;
label.text = @"I would like to ride a boat in indian ocean";
[label sizeToFit];
Upvotes: 0
Reputation: 3906
Please check the following code:
let screenRect = UIScreen.mainScreen().bounds;
let screenWidth = screenRect.size.width;
let text:String = self.label.text!
let attr:NSDictionary = [NSFontAttributeName: self.label.font];
let textSize = (text as NSString).sizeWithAttributes(attr as? [String : AnyObject])
let textWidth = textSize.width
if textWidth > screenWidth{
self.label.text = "I would like to ride a boat in\nindian ocean"
}
Upvotes: 1