[英]UItableviewcontroller SizeToFit not working on UILabel field
[英]UILabel sizeToFit with relative font size not working
如果我將多行字符串放入UILabel中,請設置相對於視圖邊界的字體大小,然后調用sizeToFit
,所有這些都發生在drawRect:
,它可以完美地調整我的標簽大小。 由於方向改變而再次調用drawRect:
,它會擰緊所需的尺寸。
在所有情況下, self.bounds.width
都遠遠大於標簽的需要。
碼:
import UIKit
class CustomView: UIView {
var label = UILabel()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.contentMode = .Redraw
addSubview(label)
}
override func drawRect(rect: CGRect) {
let string = "this is line 1\r\nand\r\nthis is line 3"
label.numberOfLines = 3
label.text = string
label.font = label.font.fontWithSize(self.bounds.width / 30)
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.textAlignment = NSTextAlignment.Center
label.sizeToFit()
label.backgroundColor = UIColor.grayColor()
label.textColor = UIColor.whiteColor()
label.center = self.center
}
}
最初,一切看起來都不錯:
但是當我的界限由於方向不同而改變時:
有任何想法我在這里做錯了嗎? 順便說一句,它是不希望增長的寬度。 因為如果我設置label.numberOfLines = 0
,它的確會增加,但只會增加高度。
事實證明,您需要在再次調用sizeToFit
之前將UILabel
的frame.size.width
和/或frame.size.height
設置為零,例如:
label.frame.size.width = 0
要么
label.frame = CGRectZero
這樣,它會再次調整大小,同時注意numberOfLines
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.