繁体   English   中英

Swift - 使用 Storyboard 的属性文本功能在以编程方式设置字体大小并运行模拟器时全部重置

[英]Swift - Attributed Text features using Storyboard all reset when setting font size programmatically and run simulator

在故事板上,我创建了一个文本视图。 在 textview 中插入了两段文本内容。 在故事板上选择自定义属性并加粗一些文字。 当我运行模拟器时,一切正常。 但是当我相对于“view.frame.height”以编程方式设置字体大小时,我在故事板上设置的粗体字会重置为常规字词。

代码:“abcTextView.font = abcTextView.font?.withSize(self.view.frame.height * 0.021)”

我无法解决这个问题。 我该如何解决这个问题?

问题是您正在使用 AttributedString。 如果您需要更多上下文,请在此处查看 Manmal 的出色回答,并解释代码的工作原理:

NSAttributedString,整体更改字体但保留所有其他属性?

这是他提供的扩展的一个简单应用,将其放在您的问题的上下文中:

class ViewController: UIViewController {

    @IBOutlet weak var myTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let newString = NSMutableAttributedString(attributedString: myTextView.attributedText)
        newString.setFontFace(font: UIFont.systemFont(ofSize: self.view.frame.height * 0.033))
        myTextView.attributedText = newString

    }

}

extension NSMutableAttributedString {
    func setFontFace(font: UIFont, color: UIColor? = nil) {
        beginEditing()
        self.enumerateAttribute(
            .font,
            in: NSRange(location: 0, length: self.length)
        ) { (value, range, stop) in

            if let f = value as? UIFont,
              let newFontDescriptor = f.fontDescriptor
                .withFamily(font.familyName)
                .withSymbolicTraits(f.fontDescriptor.symbolicTraits) {

                let newFont = UIFont(
                    descriptor: newFontDescriptor,
                    size: font.pointSize
                )
                removeAttribute(.font, range: range)
                addAttribute(.font, value: newFont, range: range)
                if let color = color {
                    removeAttribute(
                        .foregroundColor,
                        range: range
                    )
                    addAttribute(
                        .foregroundColor,
                        value: color,
                        range: range
                    )
                }
            }
        }
        endEditing()
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM