在 UITextView 中切换 selectedRange 属性

Toggle selectedRange attributes in UITextView

我创建了一个按钮,我想检查是否选择了文本,如果是,则在点击时在 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)
        }
    }
}

我们使用 enumerateAttribute(_:in:options:using:) 来查找字体(因为 bold/non-bold)在该属性中。 我们根据您的需要进行更改(粗体 <=> 非粗体)。