本文介绍了在 UITextView 中切换 selectedRange 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个按钮,我想检查是否选择了文本,然后在点击时在 selectedRange 上切换粗体和取消粗体.目前我的代码只会将 selectedRange 更改为粗体,我无法撤消它或检查是否有选择.我怎样才能做到这一点?

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

推荐答案

这或许能解决问题:

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

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

这篇关于在 UITextView 中切换 selectedRange 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 01:10