ios - 调整 NSMutableAttributedString 的字体大小与 UILabel 的框架高度成比例

标签 ios swift

在我的项目中,我使用swift 3.0。现在我正在使用以下类(UILabel子类)根据UILabel框架高度调整字体大小。 当 UILabel 框架发生变化时,layoutSubviews 会重新计算比例字体大小。

class Label: UILabel {

    // FIXME: - properties
    var fontSize: CGFloat = 0
    var frameHeight: CGFloat = 0

    // FIXME: - proportional font size adjustment
    override func layoutSubviews() {
        super.layoutSubviews()
        font = font.withSize(frame.size.height * (fontSize / frameHeight))
    }
}

如何使用:

private let id: Label = {
        let label = Label()
        label.textAlignment = .left
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
        label.textColor = UIColor(hex: 0x212121, alpha: 1)
        label.fontSize = 17
        label.frameHeight = 20
        label.clipsToBounds = true
        return label
    }()

现在我想将 UILabel 中字符串的某些部分显示为粗体文本,并保留为常规文本。所以我在这个线程上找到了一些帮助:Making text bold using attributed string in swift

我正在使用 NSMutableAttributedString 的“Prajeet Shrestha's”扩展。

// "Prajeet Shrestha's" extension
extension NSMutableAttributedString {
    func bold(_ text:String) -> NSMutableAttributedString {
        let attrs:[String:AnyObject] = [NSFontAttributeName : UIFont(name: "AvenirNext-Medium", size: 12)!]
        let boldString = NSMutableAttributedString(string:"\(text)", attributes:attrs)
        self.append(boldString)
        return self
    }

    func normal(_ text:String)->NSMutableAttributedString {
        let normal =  NSAttributedString(string: text)
        self.append(normal)
        return self
    }
}

但是当 UILabel 框架发生更改时,我不知道如何更改此 NSMutableAttributedString 的字体大小?

希望得到任何帮助。

最佳答案

试试这个

来源Looping Through NSAttributedString Attributes to Increase Font SIze

 mutableStringObj?.enumerateAttribute(NSFontAttributeName, in: NSRange(location: 0, length: mutableStringObj?.length), options: [], usingBlock: {(_ value: Any, _ range: NSRange, _ stop: Bool) -> Void in
            if value {
                var oldFont: UIFont? = (value as? UIFont)
                var newFont: UIFont? = oldFont?.withSize(CGFloat(oldFont?.pointSize * 2))
                res?.removeAttribute(NSFontAttributeName, range: range)
                res?.addAttribute(NSFontAttributeName, value: newFont, range: range)
            }
        })

关于ios - 调整 NSMutableAttributedString 的字体大小与 UILabel 的框架高度成比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43252440/

相关文章:

ios - 数据保护功能是否也会在 Core Data 的幕后保护 sqlite 文件?

swift - 在 Swift(iOS 应用程序)中,什么时候需要使用其他整数类型?

ios - addSubview 之后 View 移动

ios - 使用@IBInspectable 设置 UItextField 值

ios - 实例方法 'widgetPerformUpdate(completionHandler:)' 几乎匹配可选要求 'widgetPerformUpdate(completionHandler:)'

ios - 丢弃从右到左在 iOS 中不起作用

swift - 将 UIImage 保存到 plist 问题(SWIFT)

iphone - 如何使用 iOS5 将 Twitter 帐户关注者访问到 iPhone?

ios - 将 CAF 转换为 WAV, channel 布局 iOS

ios - 获取当前导航 Controller 的正确方法