ios - 带有属性文本的 UILabel 中的 adjustsFontForContentSizeCategory

标签 ios uilabel nsattributedstring

我想我会节省其他人的调试时间,并说将 adjustsFontForContentSizeCategory 设置为 true 对您设置 attributedText 值的标签没有影响(至少在 tableview 单元格中标签)。

幸运的是,解决方案是自己在属性字符串上设置字体。我写了一个小实用程序扩展:

public extension NSMutableAttributedString {
    public func setFont(_ font: UIFont) -> NSMutableAttributedString {
        addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: string.count))

        return self
    }
}

在何处设置要调用的 attributedText 属性

@IBOutlet weak var myLabel: UILabel!

var myAttributedString: NSAttributedString = .....

myLabel.attributedText = NSMutableAttributedString(attributedString: myAttributedString).setFont(myLabel.font)

最佳答案

public extension NSMutableAttributedString {
public func setFont(_ font: UIFont) -> NSMutableAttributedString {
    addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: string.count))

    return self
}

关于ios - 带有属性文本的 UILabel 中的 adjustsFontForContentSizeCategory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48176121/

相关文章:

ios - 限制 NSAttributedString 行数

ios - 为什么 NSAttributedString 不继承 NSString ? NSAttributedString 的父类是 NSObject 为什么?

iOS - 在 MVP 的 Presenter 中单元测试异步私有(private)函数

ios - 添加 UIImage 会忽略 UIImageView 框架并调整其大小

iphone - CABasicAnimation 保持恒定速度

ios - 如何将两个 UILabel 排成一行,以便它们根据 iOS 中文本的大小垂直居中?

ios - 将字符串数组显示为多行字符串 - Swift

ios - 3D 触摸到 UITabView

xcode - 创建多行 UILabel

swift - 如何绘制梯形(或圆形)的文字?