https://dev59.com/3oTba4cB1Zd3GeqP5mhu#26456563'
我在上面找到了这个答案,不幸的是它是用Objective C写的。- (void)highlight {
NSRange selectedTextRange = self.textView.selectedRange;
[attributedString addAttribute:NSBackgroundColorAttributeName
value:[UIColor redColor]
range:selectedTextRange];
float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
if (sysVer < 8.0) {
// iOS 7 fix
self.textView.scrollEnabled = NO;
self.textView.attributedText = attributedString;
self.textView.scrollEnabled = YES;
} else {
self.textView.attributedText = attributedString;
}
}
let selectedText = textView.selectedRange
创建属性:
let myAttribute = [ NSForegroundColorAttributeName: selectedUIColor]
提供你的属性,
textView.textStorage.addAttributes(myAttribute, range: selectedText)
在被发送者调用的动作中使用这个。
希望对你有所帮助!