在iOS的UITextView中是否可以更改选择文本的颜色?

3

默认

enter image description here

期望的

enter image description here

在UITextField上更改tintColor会更改选择颜色,但我找不到任何更改UITextView中选择颜色的文档。

2个回答

10

是的,你可以使用UITextViewtintColor属性来更改文本选择颜色。使用以下代码可获得预期输出。

self.textView.tintColor = .red

此外,您可以从storyboard中完成这个步骤,具体请参考下面的图片。

在此输入图片描述 在此输入图片描述


阅读问题他的意思是改变所选文本的颜色,你提供的将会改变整个文本的颜色。 - undefined
嗨,@HarjotSingh,特此告知,'tintColor'并不是指文本颜色,而是改变所选文本的颜色。根据给定的要求,请您再次确认并在此处留下评论。 - undefined
嗨,给我点踩的人,这段代码有什么问题?这段代码输出的结果是符合预期的。 - undefined
嗨Atul,不要介意,但是请检查其他答案,你的答案不完整。 - undefined
嗨@HarjotSingh,我已经更新了答案,请查看附图,你也可以从Storyboard中进行操作。 - undefined
完美的答案。 - undefined

0

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;
    }
}

基本上,他们创建了一个名为 highlight 的函数。在该函数中,他们寻找用户实际上高亮选定部分的情况。当他们获取到用户选择的文本范围时,他们给它添加一个属性并提供颜色。
Swift
let selectedText = textView.selectedRange

创建属性:

let myAttribute = [ NSForegroundColorAttributeName: selectedUIColor]

提供你的属性,

textView.textStorage.addAttributes(myAttribute, range: selectedText)

在被发送者调用的动作中使用这个。

希望对你有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接