how can a label display string in multiple lines - swift

I have a label which displays a string triggered by a button and some int values entered in some textfields...
However, how can I make the label's string to be in multiple lines?
I can see a lot of people have asked this question, but for some reason, when I try to follow the answers it deletes the rest of my sentence after the use of "\n", as I have just tried earlier...

If the label is created in storyboard, go to your storyboard and select it, then in the attribute inspector there is a field 'Lines' with default value of 1. change that 0 and that should work.

Try using the following code
var label:UILabel = UILabel(frame: CGRectMake(10
,100, 300, 40));
label.textAlignment = NSTextAlignment.Center;
label.numberOfLines = 0;
label.font = UIFont.systemFontOfSize(16.0);
label.text = "First label\nsecond line";
Also make sure the height of label is enough to handle the string when presented in multiline else it won't show the next line in label.
To calculate height of label according to String this link can be helpful

Related

Swift UILabel line spacing of break lines

I have a text that comes from multiple sources and ends with \n\n for a line break in UILabel that has lines set to 0 through Storyboard.
For example:
let text = “Some text at the beginning of the paragraph that is this long\n\nSecond type of text\n\nSome longer text that is on later on in the paragraph”
The output is correct:
Some text at the beginning of the paragraph that is this long
Second type of text
Some longer text that is on later on in the paragraph
I have changed the line spacing to slightly increase the gaps between lines but can’t change the height of the empty line. I want the line break to be approximately half the size of a normal line break. I tried after/before paragraph settings but can’t get an empty line to be half the size.
Any idea if this is possible and what is the best way to achieve this through storyboard or programmatically.
----- Edit:
This is what I tried:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing = 0.1
paragraphStyle.paragraphSpacingBefore = 0.1
let attrString = NSMutableAttributedString(string: text)
attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
cell.firstLabel?.attributedText = attrString

UILabel splitting in the middle of words (or how to get proper word wrapping)

I'm trying to fit some text into a fixed-width label (actually the width depends on the screen size, but cannot change within the app), and expect UIKit to cleverly use a combination of font resizing and word-wrapping to get the proper result. However, it doesn't seem to work that way. Considering a UILabel with the following constraints:
aspect ratio = 1:1
label.width = 0.7 * parentView.width (all other relevant constraints set, no errors or warnings in IB)
and the following code:
label.font = label.font.withSize(100)
label.adjustsFontSizeToFitWidth = true
label.lineBreakMode = .byClipping
label.numberOfLines = 0
label.text = "Shooter team"
I would be hoping that it would resize the text and make it fit into two lines: "Shooter" and "team" (or, since the text could be anything, split it properly into words). However, when I set label.lineBreakMode to .byWordWrapping, it doesn't resize the text at all and so only one big letter is displayed (note: I'm using a big font size for it to resize because I can't know in advance how big the text is going to be, since the size depends on the screen size). Any other value for .lineBreakMode results in the text being resized but split into "Shoote" and "r team", which looks dumb. Changing autoshrink to e.g. Minimum font size = 8 doesn't seem to have any effect. See screenshot below.
Any suggestion of how I can get the proper splitting/resizing? I may have used the wrong terms for my searches but I haven't found any answer :-|
(Note: there will be a different question about how I can get the border of the encompassing view to be a nice circle prior to the view being displayed :-| )
First, to take advantage of adjustsFontSizeToFitWidth, you must also give it a scale factor (the smallest size you're willing to let the label shrink to). So if, for example, your label's font is sized at 30, you could let it shrink down to 24:
someLabel.font = UIFont(name: "someFont", size: 30)
someLabel.adjustsFontSizeToFitWidth = true
someLabel.minimumScaleFactor = (24/30)
Second, you may want to consider using an attributed title for your label to take advantage of paragraph styling. Paragraph styling lets you play with hyphenation rules:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 1.0
let attributedTitle = NSAttributedString(string: "Shooter team", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.paragraphStyle: paragraphStyle])
someLabel.attributedText = attributedTitle
For lack of a better solution I've written the following function that empirically tries to find a font size that doesn't split a word in the middle. It's hackish but at least it works... Comments, suggestions or any better solution welcome!
func findFittingFont(for label: String) -> UIFont {
// note: the 'split' function is a personal addition that splits a string on a regex
// in this case, split between a non-word char and a word char
let words = label.split(pattern: "(?<=\\W)(?=\\w)")
var font = myLabel.font!
// the width we don't want to overflow
let maxWidth = myLabel.frame.width
var fontSize = myLabel.frame.height
var tooBig: Bool
repeat {
tooBig = false
font = font.withSize(fontSize)
// check for each word whether the rendered width is larger than the max width
for word in words {
// calculate the rendered width with the current font
let width = (word as NSString).size(withAttributes: [.font: font]).width
if width > maxWidth {
tooBig = true
// decrease the size by a factor
fontSize *= 0.9
break
}
}
// go on as long as there's an overflowing word
}
while tooBig
return font
}

Swift - UITextView maxLines is set but can type beyond

I have a UITextView that has maxLines set like this:
textView.textContainer.maximumNumberOfLines = 3;
textView.textContainer.lineBreakMode = .byTruncatingTail
textView.isScrollEnabled = false
However, when typing in the textView, you can press return several times and type beyond 3 lines. Visually, only 3 lines appear, but as you type text is being entered on and on. Is there a way to prevent this?
The maximum number of lines is used to define how many will be visible in the interface. This has nothing to do with the amount of text you type.
If you want to add a "limit" to the number of characters you have to do it programmatically.
There are several other answers related to this on SO.
How to limit characters in UITextView iOS
You can try this
textView.textContainer.maximumNumberOfLines = 3
textView.textContainer.lineBreakMode = .byTruncatingTail
textView.layoutManager.textContainerChangedGeometry(textView.textContainer)

Set height for a variable length message into a UIlabel in swift is not correct always

I wrote the following lines of code to set a variable length message into a UIlabel in swift, which works properly 9 out of 10 times. But at one time it suddenly truncated the last 2 or 3 lines from the message:
var response: AnyObject = prefs.objectForKey("response")!
response = response.stringByReplacingOccurrencesOfString("-", withString: "\n")
msglbl.numberOfLines = 0;
msglbl.text = "\(response)"
msglbl.textAlignment = .Center;
msglbl.sizeToFit()
self.view.addSubview(msglbl)
msglbl.font = UIFont(name: "Gotham-Book", size: 16)
Please let me know what I am doing wrong.
You are calling sizeToFit() before setting the label's font and size. Thus the label is being sized for the wrong font and size. Configure everything about the label first. Then size it to fit that configuration.

How to wrap a line in label in iphone?

I am new to iphone development .I want to wrap up the text in the label.I want to wrap up to a particular position in the label.Thanks.
theLabel.lineBreakMode = UILineBreakModeWordWrap;
theLabel.numberOfLines = 0;
That'll let it wrap an arbitrary number of lines. If you want to limit them, and have it truncate with a “...”, then set the numberOfLines property to that value.
Set "Line breaks" in Interface Builder ( http://drp.ly/d3K65 ) to "Word Wrap" and increase height of the UILabel.
You can do the same thing (or even more complex) in the code, see UILabel reference http://developer.apple.com/iPhone/library/documentation/UIKit/Reference/UILabel_Class/Reference/UILabel.html