简体   繁体   中英

UILabel not respecting truncate

This is puzzling me for a while. This is my code:

 let label:UILabel = UILabel(frame: CGRectMake(0, 0, obTextRect.width, obTextRect.height))
            label.text = stText
            label.backgroundColor = UIColor.redColor()
            label.textAlignment = NSTextAlignment.Center
            label.numberOfLines = 0
            label.lineBreakMode = NSLineBreakMode.ByTruncatingTail
            label.font = obDrawItem.m_obFont
            label.adjustsFontSizeToFitWidth = true
            label.minimumScaleFactor = 0.1
            label.layer.drawInContext(obContext)


            CGContextRestoreGState(obContext)

and this is the result I am getting...

proceedin
g

The word "proceeding" does not "auto shrink" to fit the width. Also if I add a line break (\\n) then it works ok. Any ideas???

The code works absolutely correctly. Why?

  1. The text doesn't shrink because it fits into its frame.

  2. The text doesn't use truncation because it fits into its frame.

  3. Word wrapping is ignored because the word doesn't fit into single line.

I would advise you to set wrapping properties dynamically, depending on content. If the text has only one word, then set numberOfLines to 1 , otherwise set it to 0 or 2-3 . That will fix most of your problems.

let multipleWords = stText.rangeOfCharacterFromSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) != nil
label.numberOfLines = multipleWords ? 0 : 1

Try this:

label.numberOfLines = 1

Setting numberOfLines to 0 makes the label multi-line.

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