使 TextView 的文本颜色的一半不同于其他 50% 的文本 SWIFT

Posted

技术标签:

【中文标题】使 TextView 的文本颜色的一半不同于其他 50% 的文本 SWIFT【英文标题】:Make half of the TextView's text color Different than other 50% of the text SWIFT 【发布时间】:2019-05-15 04:07:44 【问题描述】:

我的 UITextView 中有一个大文本,我想将文本颜色的 50% 设为 red ,将其他 50% 设为 green 。我在 TextView 中添加了 NSMutableAttributedString 但它适用于整个文本范围。如何将textView的文本分成两部分,分别着色为红色和绿色?

let strNumber: NSString = self.text as NSString // TextView Text
        let range = (strNumber).range(of: strNumber as String)
        let attribute = NSMutableAttributedString.init(string: strNumber as String)
        attribute.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14) , NSAttributedString.Key.foregroundColor : UIColor.red], range: range)
        self.attributedText = attribute

【问题讨论】:

【参考方案1】:

您似乎有UITextView 的扩展名。以下扩展函数将使文本视图的现有属性文本变为半红半绿。所有其他现有属性(如果有)都将保留。

extension UITextView 
    func makeHalfRedGreen() 
        if let text = self.text 
            let half = text.count / 2
            let halfIndex = text.index(text.startIndex, offsetBy: half)
            let firstRange = NSRange(..<halfIndex, in: text)
            let secondRange = NSRange(halfIndex..., in: text)
            let attrTxt = NSMutableAttributedString(attributedString: attributedText)
            attrTxt.addAttribute(.foregroundColor, value: UIColor.red, range: firstRange)
            attrTxt.addAttribute(.foregroundColor, value: UIColor.green, range: secondRange)
            attributedText = attrTxt
        
    

【讨论】:

【参考方案2】:

尝试使用如下函数

text_lbl.attributedText = self.decorateText(txt1: "Red Color", txt2: “Blue Color”)


func decorateText(txt1:String, txt2:String)->NSAttributedString
    let textAttributesOne = [NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont(name: "Poppins-Regular", size: 12.0)!] as [NSAttributedStringKey : Any]
    let textAttributesTwo = [NSAttributedStringKey.foregroundColor: UIColor.blue, NSAttributedStringKey.font: UIFont(name: "Poppins-SemiBold", size: 14.0)!] as [NSAttributedStringKey : Any]

    let textPartOne = NSMutableAttributedString(string: txt1, attributes: textAttributesOne)
    let textPartTwo = NSMutableAttributedString(string: txt2, attributes: textAttributesTwo)

    let textCombination = NSMutableAttributedString()
    textCombination.append(textPartOne)
    textCombination.append(textPartTwo)
    return textCombination

【讨论】:

以上是关于使 TextView 的文本颜色的一半不同于其他 50% 的文本 SWIFT的主要内容,如果未能解决你的问题,请参考以下文章

更改 android studio 中的 textview 可见性

如何获取 android TextView 的默认文本颜色?

textview中文本的默认颜色是啥?

如何在listview android中使文本颜色透明?

Android Studio IDE - 终端背景文本颜色不同于终端背景颜色

textview可以有不同颜色的字母吗? [复制]