我无法更改以编程方式创建的 UILabel
中文本的大小。
这是一个屏幕截图:
这是类定义:
class myView: UIView {
let theLabel = UILabel()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.theLabel.text = "Text"
self.theLabel.backgroundColor = UIColor.lightGray
self.backgroundColor = UIColor.blue
self.theLabel.adjustsFontSizeToFitWidth = true
self.theLabel.textAlignment = .center
self.theLabel.numberOfLines = 1
self.theLabel.minimumScaleFactor = 0.1
self.theLabel.font = UIFont( name: "System", size:160)
self.theLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.theLabel)
let selfAspectConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.width, multiplier: 1.0, constant: 0)
let labelWidthConstraint = NSLayoutConstraint(item: self.theLabel, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.width, multiplier: 0.5, constant: 0)
let heightConstraint = NSLayoutConstraint(item: self.theLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: self.theLabel, attribute: NSLayoutAttribute.width, multiplier: 0.5, constant: 0)
let xConstraint = NSLayoutConstraint(item: self.theLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)
let yConstraint = NSLayoutConstraint(item: self.theLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
self.addConstraints([selfAspectConstraint,labelWidthConstraint, heightConstraint,xConstraint,yConstraint])
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
我试过更改字体大小。我已将 adjustsFontSizeToFitWidth
设置为 true 并设置 minimumScaleFactor
。文本大小始终相同。我希望它填满标签区域,即灰色框。
我如何让它工作?
最佳答案
尝试在设置字体后添加这一行: self.theLabel.font = theLabel.font.withSize(45)
关于ios - 无法更改以编程方式创建的 UILabel 中的文本大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41309408/