我的UITextView中有一个大文本,我想将文本的50%设置为红色,将其他50%设置为绿色。我在TextView中添加了NSMutableAttributedString,但是它适用于整个文本范围。如何将textView的文本分为两部分,并用红色和绿色上色?
import moment from "moment";
const validateDate = ({ date }) => {
return moment(date, "DD-MM-YYYY").isSameOrAfter(
moment(new Date(), "DD-MM-YYYY", "days")
);
};
export default validateDate;
答案 0 :(得分: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
}
}
}
答案 1 :(得分:0)
尝试使用如下功能
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
}
答案 2 :(得分:-2)
尝试使用textView委托的textView:shouldChangeTextInRange:replacementText协议