簡體   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