Toggle selectedRange attributes in UITextView

前端 未结 1 1418
闹比i
闹比i 2021-01-27 10:18

I have created a button that I want to check if text is selected then if so toggle bold and unbold over the selectedRange when tapped. At the moment my code will just change the

相关标签:
1条回答
  • 2021-01-27 10:53

    This might do the trick:

    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:) to look for fonts (since bold/non-bold) is in that attribute. We change it according to your needs (bold <=> unbold).

    0 讨论(0)
提交回复
热议问题