在UITextView中切换selectedRange属性

时间:2019-05-07 11:43:41

标签: swift nsattributedstring uifont

我创建了一个按钮,我想检查是否选择了文本,如果是,则点击时在选中的范围上切换粗体和粗体。目前,我的代码只会将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)
    }

1 个答案:

答案 0 :(得分:1)

这可能会达到目的:

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:)查找该属性中的字体(因为粗体/非粗体)。 我们会根据您的需要进行更改(粗体<=>粗体)。