【问题标题】:Is it possible to change selection color in UITextView iOS?是否可以在 UITextView iOS 中更改选择颜色?
【发布时间】:2019-07-15 11:11:14
【问题描述】:

默认

希望

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

【问题讨论】:

    标签: ios swift cocoa-touch uitextview


    【解决方案1】:

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

    self.textView.tintColor = .red
    

    此外,您可以从情节提要中执行此操作,请参见下图。

    【讨论】:

    • 阅读他的意思是改变所选文本的颜色,您提供的内容将改变整个文本的颜色。
    • 嗨,@HarjotSingh 为您提供的类信息 'tintColor' 不是文本颜色,tintColor 更改选择文本颜色,根据给定的要求,请检查一次,然后将评论放在这里。
    • 嗨 Downvoter 这个代码有什么问题,这个代码 id 给出了预期的输出。
    • 嗨 Atul,没有冒犯,但请检查另一个答案,您的答案不完整。
    • 嗨@HarjotSingh 我有更新的答案请参阅附图,您也可以从情节提要中执行此操作。
    【解决方案2】:

    https://stackoverflow.com/a/26456563/8272698'

    我在上面找到了这个答案,不幸的是它在目标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 的函数。 在用户实际突出显示所选部分时,他们正在寻找的功能中。 self.textView.selectedRange 当他们获得用户选择的文本范围时。他们给它一个属性并为其提供颜色。

    斯威夫特

    let selectedText = textView.selectedRange
    

    创建属性:

    let myAttribute = [ NSForegroundColorAttributeName: selectedUIColor]
    

    提供你的属性,

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

    在发件人调用的操作中使用它。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2015-04-22
      • 1970-01-01
      • 2010-10-16
      • 2018-10-06
      • 2012-12-23
      • 2017-07-09
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      相关资源
      最近更新 更多