Сделайте половину цвета текста TextView отличным от других 50% текста SWIFT - PullRequest
0 голосов
/ 15 мая 2019

У меня большой текст в UITextView, и я хочу сделать 50% цвета текста красным, а остальные 50% зеленым. Я добавил NSMutableAttributedString в TextView, но он работает для всего диапазона текста. Как разделить текст 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

Ответы [ 3 ]

1 голос
/ 15 мая 2019

Кажется, у вас есть расширение до 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
        }
    }
}
0 голосов
/ 15 мая 2019

Попробуйте использовать функцию, как показано ниже

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
}
0 голосов
/ 15 мая 2019

Попробуйте textView: shouldChangeTextInRange: замена текстового протокола делегата textview

...