【发布时间】:2019-05-14 04:57:28
【问题描述】:
我正在尝试创建一个UIButton,它允许选定的文本带有下划线。这是我当前的代码:
func underline() {
if let textRange = selectedRange {
let attributedString = NSMutableAttributedString(attributedString: textView.attributedText)
textView.textStorage.addAttributes([.underlineStyle : NSUnderlineStyle.single.rawValue], range: textRange)
}
}
目前正在下划线,但我遇到的问题是我需要检查当前文本是否已经下划线以及是否删除了下划线。我似乎无法用NSMutableAttributedString 解决这个问题。
我正在使用斜体 UIButton 这样做:
func italic() {
if let textRange = selectedRange {
let attributedString = NSAttributedString(attributedString: textView.attributedText)
attributedString.enumerateAttribute(.font, in: textRange, options: []) { (font, range, pointee) in
let newFont: UIFont
if let font = font as? UIFont {
let fontTraits = font.fontDescriptor.symbolicTraits
if fontTraits.contains(.traitItalic) {
newFont = UIFont.systemFont(ofSize: font.pointSize, weight: .regular)
} else {
newFont = UIFont.systemFont(ofSize: font.pointSize).italic()
}
textView.textStorage.addAttributes([.font : newFont], range: textRange)
}
}
}
}
如何才能检查当前文本是否具有我的第一个函数的下划线属性?
到目前为止我们的代码:
func isUnderlined(attrText: NSAttributedString) -> Bool {
var contains: ObjCBool = false
attrText.enumerateAttributes(in: NSRange(location: 0, length: attrText.length), options: []) { (dict, range, value) in
if dict.keys.contains(.underlineStyle) {
contains = true
}
}
return contains.boolValue
}
func underline() {
if let textRange = selectedRange {
let attributedString = NSMutableAttributedString(attributedString: textView.attributedText)
switch self.isUnderlined(attrText: attributedString) {
case true:
print("true")
textView.textStorage.removeAttribute(.underlineStyle, range: textRange)
case false:
print("remove")
textView.textStorage.addAttributes([.underlineStyle : NSUnderlineStyle.single.rawValue], range: textRange)
}
}
}
【问题讨论】:
标签: ios swift uitextview nsattributedstring nsmutableattributedstring