如何检查文本是否有下划线

How to check if text is underlined

我正在努力确定 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)
    }
}

我相信下划线不是字体特征的一部分,它一定是文本的一个属性。您可能会发现这个问题的答案很有用。我希望它能帮助你!