gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:26:57 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

NSAttributedString, change the font overall BUT keep all other attributes?

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

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()
}
}

关于Swift - 当以编程方式设置字体大小并运行模拟器时,使用 Storyboard的属性文本功能全部重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59973753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com