Adding multiple Lines of text into UILabel in swift - ios

Hi I want to display some text in my UILabel line by line when an action is occurred
Hi, I have a textbox, button and a UILabel, lets say I've typed in
"This text will be displayed line by line in a UILabel"
and pressed the button to display the text in the UILabel..
so inside the UILabel it will look like:
This
text
will
be
displayed
line
by
line
in
a
UILabel
....
I've been searching forums but could not found an answer.. so I don't know if this is possible.. please help
p.s I've set number of lines to 0 and line breaks is set to word wrap

let label = UILabel(frame: CGRect(x: 100, y: 100, width: 100, height: 300)) // make the height biggest
// label.lineBreakMode = NSLineBreakMode.ByWordWrapping
// label.numberOfLines = 0
dont work if label width bigger word width
var string = "This text will be displayed line by line in a UILabel"
var array = string.componentsSeparatedByString(" ")
var newstring = join("\r", array)
label.text = newstring

let labelText = "Write\rthe\rtext\rwith\rline\rbreaks."

In order to wrap your text within a UILabel on Xcode 6 and above
Select the label you are working with.
Navigate to the Utilities panel.
Select the "Attributes inspector"
Select the number of lines you would like to display on the label (2,3,4) depending on the size of your UILabel field
Select "Word Wrap" under Line Breaks, or you can select any option of your preference.
You may manipulate the way your text appears to your taste.

Does it have to be a UILabel?
You could use UITextField instead which has some advantageous handling options

Related

Splitting a string truncates the word in UILabel

I try to setup a custom button with UIImage and UILabel
After setting up constraints, I started testing this button and noticed strange behavior
UILabel in UIButton code:
private var title: UILabel = {
var label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.boldSystemFont(ofSize: 14)
label.numberOfLines = 0
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
return label
}()
When I set title for example "Hfpdktxtybz", UILabel works amazing!
One word takes one line:
But if I try set title for example "Развлечения", UILabel truncates the word.
One word is split into two lines:
Why for English language label work is correctly, but for Russian language truncates the word? How to fix it?
The number of characters is the same
The problem is, as said in the comments, that characters don't necessarily have the same width.
lllll
AAAAA
aaaaa
The above example clearly shows characters do not have the same width although they have same character count.
So Autolayout calculates the UILabel real width and it has only one option in order to satisfy your constraints. That is to split it into 2 lines.
If you don't want this to happen consider changing UILabel priority numberOfLines.
if you use storyboard
if you use swift programmatically.
label.numberOfLines = 2

Intrinsic content size of button with text only

I have a uibutton, i want to set text dynamically at run time with padding top: 10, bottom 10 and left: 10 and right: 10, once i set text button title cliped. Any one can provide solution.
You must be attentive to fontSize of the button. Setting text programmatically doesn't automatically fits the text. Following code will help you.
//Swift
let btnLabel = yourButton.titleLabel
btnLabel.adjustsFontSizeToFitWidth = true
//Objective C
UILabel *btnLabel = yourButton.titleLabel;
btnLabel.adjustsFontSizeToFitWidth = true
Happy Coding <3

UILabel on second line if the content doesn't fit in the view's first line

The best way to describe my situations is with images. What I have is a view which contains several UILabels and UIImage. The red box is a UILabel and if the content is too big it should go to the second line.
From the storyboard I have a working case when the content fits but the problem is that I am not sure how to handle the case when the last (red box) should go to the second line. I am using autolayout and cartography.
If someone can point me to the right direction I will be very grateful.
First calcululate width of text as per your current label's position.
If text width is more than current label's width then see my answer from below link:
Auto Layout how to move the view2 from right to the bottom?
Calculate width:
func widthForView1(_ text:String, font:UIFont, height:CGFloat) -> CGFloat
{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: your_label_width, height: your_lable_height))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.text = text
label.font = font
label.sizeToFit()
return label.frame.width
}
You cannot do that with constraints only. To change the entire position of the element on the screen, you need to do it programmatically.
Use of tag View can solve this issue. TagListView is an external library.
When u add a view as subclass of taglistView, its height automatically increases accordingly.
ADD this to pod file : pod 'TagListView'
func addTags() {
let str1 = "Hi"
tagListView.addTag(str1)
let str2 = "Helloo"
tagListView.addTag(str2)
let str3 = "How Are u ? "
tagListView.addTag(str2)
tagListView.isUserInteractionEnabled = false
}

Adjust font size of text to fit in UIButton

I want to make sure the button text fits into a UIButton, while the UIButton has a fixed size.
Of course I can access the titleLabel of the UIButton.
In a label I would set autoshrink to minimum font scale which seems to correspond to
self.myButton.titleLabel.adjustsFontSizeToFitWidth = YES;
, but doesn't really behave the same, since it only makes the text fits horizontally into the bounds, not vertically, thereby not changing the font size.
How can i actually adjust the font size of a label programmatically to make the text fit into the label bounds (as shown in Goal in the picture below) ?
I already tried
self.myButton.titleLabel.numberOfLines = 0;
self.myButton.titleLabel.minimumScaleFactor = 0.5f;
without success, always ended up as in adjustsFontSizeToFitWidth on the left side of the pic above.
Edit: The solution also has to be ios7 compliant
self.mybutton.titleLabel.minimumScaleFactor = 0.5f;
self.mybutton.titleLabel.numberOfLines = 0; <-- Or to desired number of lines
self.mybutton.titleLabel.adjustsFontSizeToFitWidth = YES;
... did the trick, after layoutIfNeeded in viewDidLoad
As it turns out, all those must be set to actually adjust the font-size, not just making it fit into the frame.
Update for Swift 3:
mybutton.titleLabel?.minimumScaleFactor = 0.5
mybutton.titleLabel?.numberOfLines = 0 <-- Or to desired number of lines
mybutton.titleLabel?.adjustsFontSizeToFitWidth = true
Updated code for Swift 3.0:
yourButton.titleLabel?.minimumScaleFactor = 0.5
yourButton.titleLabel?.numberOfLines = 0
yourButton.titleLabel?.adjustsFontSizeToFitWidth = true
You can also set a User Defined Runtime Attribute in Interface Builder for the button where
titleLabel.adjustsFontSizeToFitWidth = true
to make text horizontally and vertically fit with button bounds :
1 - set button alignment like image (* VERY IMPORTANT *)
2 - add this lines of code in your ViewController
btnTest.setTitle("Test for multi line in button show line in button show Test for multi line in button show line in button show", for: .normal)
btnTest.titleLabel!.textAlignment = .center
btnTest.titleLabel!.numberOfLines = 0
btnTest.titleLabel!.adjustsFontSizeToFitWidth = true
btnTest.titleLabel!.minimumScaleFactor = 0.5
// below line to add some inset for text to look better
// you can delete or change that
btnTest.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
note that DON'T using btnTest.titleLabel!.lineBreakMode = NSLineBreakMode.byWordWrapping or other BreakMode in your code . for enable multiline in button . just using from above code
final result :
Try to call the following method.
button.titleLabel?.baselineAdjustment = UIBaselineAdjustment.AlignCenters
try this:
[myButton setFont:[[myButton font] fontWithSize:--originalButtonFontSize]];
textWidth = [text sizeWithFont:[myButton font]].width;
}
In Storyboard, Go to Link Break in Attributes Inspector, see word wrap..or set according to your choice.
In Xcode->Open storyboard->Go to attributes inspector->Control->Alignment->Choose second in both horizontal and vertical.
or
YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
If you prefer do in storyboard, just click the button, then show attributes inspector, and set the line break to "Word Wrap".

Label in a UITableViewCell, change second line font size, add margins?

I have a tableview that uses UITableViewCell and is populated by data from parse.com. In the UITableViewCell there is a LABEL that has 2 lines, that shows data from parse.com.
I am wondering if it is possible to change the font size of the second line of the LABEL (leave the first line's font size the same), also is there is there a way to add margins to the left and right of the label?
EDIT: mistyped, i want to change the font size of the second line of a LABEL, as well as add margins to the left and right of the label.
In my solution I have made an used the attributedText of the UILabel to add attributed string to the label
var attributedString = NSMutableAttributedString(string:"My first line \n")
//creating NSMutableAttributedString that will be later appended with your second line
var secondLine = "My attributed second line"
let secondLineAttribute = [NSFontAttributeName : UIFont(name: label.font.fontName, size: 22)!]
//replace 22 with the size of text you want for second line
var newAttributedSecondLine: NSAttributedString = NSAttributedString(string: secondLine, attributes: secondLineAttribute)
attributedString.appendAttributedString(newAttributedSecondLine)
label.attributedText = attributedString
Dont forget to add label.numberOfLines=2 before the above code
Try this:
cell.textLabel!.font = UIFont(name: "Gotham-Book", size: 16)
Hope this might help you.
UITableViewCell has two labels textLabel and detailTextLabel if created with Subtitle style. Configure detailTextLabel as you like. Otherwise make your own UITableViewCell subclass.

Resources