Swift - 无法更改 UILabel 中的字体样式

标签 swift

我在没有 Storyboard的情况下编码。我正在以编程方式将 UILabels 添加到 ViewControllers 中,如下所示,但不知何故字体样式保持默认。有人可以告诉我的代码有什么问题吗?谢谢!

let label: UILabel = {

    let label = UILabel()

    label.font = UIFont(name: "Avenir-Light", size: 20)
    let attributedText = NSMutableAttributedString(string: "Text.", attributes: [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 20)])

    // Letter spacing
    attributedText.addAttribute(NSAttributedStringKey.kern, value: 1.5, range: NSRange(location: 0, length: attributedText.length - 1))

    // Charactor spacing
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 4
        attributedText.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedText.length))

    label.attributedText = attributedText

    return label

}()

最佳答案

属性文本的字体优先于标签本身的字体。并且您已明确定义属性文本以使用 UIFont.systemFont(ofSize: 20)

我建议将您的字体用于属性字符串:

let font = UIFont(name: "Avenir-Light", size: 20)
let attributedText = NSMutableAttributedString(string: "Text.", attributes: [.foregroundColor: UIColor.black, .font: font])

或者从属性字符串中省略它并使用标签的默认字体:

label.font = UIFont(name: "Avenir-Light", size: 20)
let attributedText = NSMutableAttributedString(string: "Text.", attributes: [.foregroundColor: UIColor.black])

关于Swift - 无法更改 UILabel 中的字体样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48843584/

相关文章:

swift - 在快速帮助文档评论中添加指向 Swift 类的链接?

swift - 一切都从 `protocol can only be used as a generic constraint because it has Self or associated type requirements`开始

swift - 尝试在另一个数组中使用可解码结构时出现可解码错误

ios - 设置 UIContextualAction 大小

swift - 将全部大写的字符串转换为只有每个单词大写的首字母

ios - 在 iOS 上拍摄照片时出现随机错误

ios - 来自任何地方的初始 View Controller

swift - Swift 3 中的 Firebase 持久性

image - 如何创建图像拼贴画?

ios - 将相机添加到用户在 map 上的当前位置