Toggle selectedRange attributes in UITextView

£可爱£侵袭症+ 提交于 2020-01-22 02:23:25

问题


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 selectedRange to bold and I can't undo it or check if there is a selection. How can I achieve this?

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)
    }

回答1:


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).



来源:https://stackoverflow.com/questions/56021846/toggle-selectedrange-attributes-in-uitextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!