2017-02-07 4 views
0

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 

Есть ли хорошее решение или мне нужно изменить каждый цвет атрибутов по одному?

Как уже отмечалось, для выбранного пользователя установлено значение true.

ответ

0

Вы можете попробовать этот код:

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 

Надеется, что это код справки.