我已经创建了一个按钮,我想检查是否选择了文本,然后如果选择了文本,则在点击时在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:)来查找该属性中的字体(因为粗体/非粗体)。
我们会根据您的需要进行更改(粗体unbold)。

关于swift - 在UITextView中切换selectedRange属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56021846/

10-09 03:12