简体   繁体   中英

Disable Line Wrapping in a multi-line UILabel

Is there a way with a multi-line label (myLabel.numberOfLines = 0) to disable any kind of line wrapping so that if a line is too long to fit on one line of the label it just stops/kind of breaks off and doesnt wrap to the line below? So I can use "\\n" to assign strings to other lines of the label. I know lines that are too long automatically wrap to the next line but I dont know if there is a no line wrap option.

So If I had a label with a line max of 10 chars per line

var firstLine : String = "This is 16 chars"
var secondLine : String = "This is too long"
myLabel.text = firstLine + secondLine
// It would look like this:

Output:

This is 16
This is to

As shown it just cuts off and doesnt wrap each line even though they dont fit

If you have desired length of your label, you can try this stupid but work method: To cut the string by yourself, use stringByPaddingToLength method.

Try below codes:

self.tempLabel.text = @"This is 16 chars fbaebfbefbefbeif";
self.tempLabel.text = [self.tempLabel.text stringByPaddingToLength:10 withString:@"" startingAtIndex:0];

See magic happens

firstLine + secondLine will become 1 string This is 16 charsThis is too long , i dont think you can do something like described without code, you have to manually cut off the strings to 10 characters and add \\n at the end, so it will become This is 16\\nThis is to

Something like :

var string = message
let fontAttributes = [NSFontAttributeName: font]
var size = (string as NSString).sizeWithAttributes(fontAttributes)

while size.width > label.width {
        string.removeAtIndex(string.endIndex.predecessor())
        size = (string as NSString).sizeWithAttributes(fontAttributes)
}
string = string+"\n"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM