ios - 更改了子字符串的颜色,但字体设置已重置

标签 ios swift swift3 uitextview

How to change color of text stirngs inside UITextView in Swift3

我尝试像这样引用上面的网址来更改子字符串的颜色。

enter image description here

func textViewDidChange(_ textView: UITextView, pageIndex: Int) {
    let attrStr = NSMutableAttributedString(string: textView.text)
    let inputLength = attrStr.string.characters.count
    let searchString = self.emphasisingWordList[pageIndex]
    let searchLength = searchString.characters.count
    var range = NSRange(location: 0, length: attrStr.length)

    while (range.location != NSNotFound) {
        range = (attrStr.string as NSString).range(of: searchString, options: [], range: range)
        if (range.location != NSNotFound) {
            attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSRange(location: range.location, length: searchLength))
            range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
            textView.attributedText = attrStr
        }
    }
}

但是,我发现设置属性文本时,字体大小和颜色会重置为默认值(黑色)。

我在代码末尾添加了这些行,但当然整个字符串都会受到影响。

self.sloganTextView.font = UIFont.systemFont(ofSize: 35)
self.sloganTextView.textColor = UIColor.white

有什么好的解决办法还是必须把每个属性颜色都一一改掉?

正如很多人已经提到的,selectable 设置为 true。

最佳答案

您可以尝试以下代码:

var strName: String = "ABC"
var strTitle: String = "XYZ"
let commentString = NSMutableAttributedString(string: strTitle + " \(strName)")
commentString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSRange(location: 0, length: (strTitle.characters.count )))
commentString.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSRange(location: (strTitle.characters.count ), length: (strName.characters.count ) + 1))
self.txtView.attributedText = commentString

希望这段代码对您有帮助。

关于ios - 更改了子字符串的颜色,但字体设置已重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42082558/

相关文章:

ios - Metal 质感比原图暗

ios - Xcode 8 Storyboard问题

ios - 带有 UIAlertAction swift 的增量标签栏角标(Badge)?

ios - 更新一个 ViewController 中的 NSUserDefaults 数据在另一个 ViewController 中更改

swift - uiactivity 和 uiwebview 委托(delegate)

swift - 从字符串中删除\\u{e2} 个字符

ios - 核心蓝牙 : detect device out of range/connection timeout

iphone - iOS 版 ImageMagick 是否支持将 jpeg 图像转换为 GIF?

ios - 如果 IBOutlet 在 UIViewController 类中,如何访问 UITableViewController 类中的 IBOutlet

ios - 单元格中的标签文本不完整或延迟