我创建了一个按钮,我想检查是否选择了文本,然后在点击时在 selectedRange 上切换粗体和非粗体。目前,我的代码只会将 selectedRange 更改为粗体,我无法撤消它或检查是否有选择。我怎样才能实现这个目标?
func bold() {
if let textRange = selectedRange {
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.bold)]
noteContents.textStorage.addAttributes(attributes as [NSAttributedString.Key : Any], range: textRange)
}
这可能会起作用:
func toggleBold() {
if let textRange = selectedRange {
let attributedString = NSAttributedString(attributedString: noteContents.attributedText)
//Enumerate all the fonts in the selectedRange
attributedString.enumerateAttribute(.font, in: textRange, options: []) { (font, range, pointee) in
let newFont: UIFont
if let font = font as? UIFont {
if font.fontDescriptor.symbolicTraits.contains(.traitBold) { //Was bold => Regular
newFont = UIFont.systemFont(ofSize: font.pointSize, weight: .regular)
} else { //Wasn't bold => Bold
newFont = UIFont.systemFont(ofSize: font.pointSize, weight: .bold)
}
} else { //No font was found => Bold
newFont = UIFont.systemFont(ofSize: 17, weight: .bold) //Default bold
}
noteContents.textStorage.addAttributes([.font : newFont], range: textRange)
}
}
}
We use enumerateAttribute(_:in:options:using:)
查找字体(因为粗体/非粗体)位于该属性中。
我们根据您的需要更改它(粗体非粗体)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)