ios - 无法更改以编程方式创建的 UILabel 中的文本大小

标签 ios swift text uilabel size

我无法更改以编程方式创建的 UILabel 中文本的大小。

这是一个屏幕截图:

screen grab

这是类定义:

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/

相关文章:

mysql : update table field type to Clob

ios - 在 NSAttributedString 中垂直居中两种不同大小的字体

ios - 通过点击 X 按钮识别 AVPlayerViewController 何时关闭

ios - 向用户显示解析设备 token

ios - 使用 swift 检查从图库中选择的模式 uiimage

ios - 错误 : Cannot subscript a value of type '[String : Any]' with an index of type 'UIImagePickerController.InfoKey'

text - 如何在 ImageMagick 中以角度方向书写文本?

CSS:Max-Width 不会缩小?

iphone - 如何在我的 iPhone 应用程序中使用 NSError?

ios - 如何解决 iOS UITableView 在滚动时覆盖 UILabel 和 UITextField?