问题描述
我正在努力确定UITextView中的某些选定文本是否带有下划线。我可以使用以下代码轻松检查粗体,斜体等内容:
let isItalic = textView.font!.fontDescriptor.symbolicTraits.contains(.traitItalic)
但是,我不知道如何检查下划线?
解决方法
我刚刚创建了一个示例项目,我认为您可以执行以下操作:
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let attrText1 = NSMutableAttributedString(string: "TestTest",attributes: [.foregroundColor : UIColor.systemTeal,.underlineStyle: NSUnderlineStyle.single.rawValue])
let attrText2 = NSAttributedString(string: " - not underlined",attributes: [.foregroundColor : UIColor.red])
attrText1.append(attrText2)
textView.attributedText = attrText1
}
func isTextUnderlined(attrText: NSAttributedString?,in range: NSRange) -> Bool {
guard let attrText = attrText else { return false }
var isUnderlined = false
attrText.enumerateAttributes(in: range,options: []) { (dict,range,value) in
if dict.keys.contains(.underlineStyle) {
isUnderlined = true
}
}
return isUnderlined
}
@IBAction func checkButtonDidTap(_ sender: UIButton) {
print(isTextUnderlined(attrText: textView.attributedText,in: textView.selectedRange))
}
}
创建扩展名以将selectedRange
设为NSRange
:
extension UITextInput {
var selectedRange: NSRange? {
guard let range = selectedTextRange else { return nil }
let location = offset(from: beginningOfDocument,to: range.start)
let length = offset(from: range.start,to: range.end)
return NSRange(location: location,length: length)
}
}
,
我认为下划线不是字体特征的一部分,而必须是文本的属性。您可能会发现此问题的答案很有用。希望对您有帮助! Enumerate over a Mutable Attributed String (Underline Button)