【问题标题】:Setting font requires size that overrides sizeToFit() Swift设置字体需要覆盖 sizeToFit() Swift 的大小
【发布时间】:2016-12-12 18:37:12
【问题描述】:

我正在制作一个标签,并尝试将字体设置为“Avenir”,如下所示:

    let usernameLabel: UILabel
    usernameLabel = UILabel(frame: CGRect(x: 20, y: third * screenHeight + sixth * screenHeight, width: third * screenWidth, height: 30))
    usernameLabel.text = "Username"
    usernameLabel.font = UIFont(name: "Avenir", size: 30) // Where I set the font
    usernameLabel.sizeToFit()
    usernameLabel.textColor = UIColor.gray()
    self.view.addSubview(usernameLabel)

但是我希望使用 usernameLabel.sizeToFit() 动态调整大小,但这没有效果,因为我必须在设置字体时设置大小,如果我尝试不使用大小选项,它会返回错误.

【问题讨论】:

  • 试试 [usernameLabel setAdjustsFontSizeToFitWidth:YES];

标签: ios iphone swift fonts font-size


【解决方案1】:

听起来您想缩放字体以适应框架大小。

所以替换:

usernameLabel.sizeToFit()  // Modify the frame to fit the label

与:

usernameLabel.adjustsFontSizeToFitWidth = true // Modify the font size to fit the frame

【讨论】:

    【解决方案2】:

    你可以试试这样的,

    let str = "your string" as NSString
    
        if let font = UIFont(name: "Arial", size: 30) {
    
            let size  = str.sizeWithAttributes([NSFontAttributeName : font])
    
            label.frame = CGRectMake(x, y, size.width, height)
            label.text = "your string"
        }
    

    【讨论】:

      猜你喜欢
      • 2012-11-28
      • 1970-01-01
      • 2014-03-27
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多