【问题标题】:Swift 3 Change color of selected text in UITextViewSwift 3 更改 UITextView 中选定文本的颜色
【发布时间】:2017-04-25 11:27:53
【问题描述】:

我刚刚将代码从 swift 2.3 更改为 Swift 3。以下代码在 swift 2.3 上运行良好,但在 swift 3 上没有效果。

我想开发一个自定义文本编辑器。并让用户选择文本并更改其颜色。为此,我正在使用此代码。

let selectedRange = textView.selectedRange

        let currentAttr = textView.textStorage.attributes(at: selectedRange.location, effectiveRange: nil)

        var attrName = NSForegroundColorAttributeName

        if !isForeGround{
            attrName = NSBackgroundColorAttributeName
        }

        if currentAttr[attrName] == nil || currentAttr[attrName] as! UIColor != selectedUIColor{

            let dict = [attrName:selectedUIColor]

            let currentFont = currentAttr[NSFontAttributeName]
            let fontDescriptor = (currentFont! as AnyObject).fontDescriptor
            let updatedFont = UIFont(descriptor: fontDescriptor!, size: 0.0)
            let dict2 = [NSFontAttributeName: updatedFont]

            textView.textStorage.beginEditing()

            if currentAttr.count>0{
                textView.textStorage.addAttributes(dict, range: selectedRange)
            }else{
                textView.textStorage.setAttributes(dict, range: selectedRange)
            }
            textView.textStorage.addAttributes(dict2, range: selectedRange)
            textView.textStorage.endEditing()
        }

运行成功,但对文本颜色没有影响。

【问题讨论】:

  • 嗨,你找到解决办法了吗?

标签: swift3 uitextview textcolor


【解决方案1】:

这对我有用。

首先你需要捕捉你选择的文本,用:

let selectedText = textView.selectedRange

然后,您创建属性:

let myAttribute = [ NSForegroundColorAttributeName: selectedUIColor]

最后:

textView.textStorage.addAttributes(myAttribute, range: selectedText)

这必须在任何发件人调用的 Action 中

希望它也适用于您! 问候

【讨论】:

    【解决方案2】:

    选中的文字可以用

    改变
    self.textView.tintColor = .red
    

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      • 2015-03-24
      • 1970-01-01
      • 2013-10-06
      • 2011-12-31
      相关资源
      最近更新 更多