如何更改 UITextView 超链接选择背景颜色?

How to change UITextView Hyperlink selection background color?

我正在使用 UITextView 使主题标签可选择。它完美地检测水龙头。我的问题是选择颜色。它看起来是黑色的,我希望文本在选择时淡化一点。 这是我现在得到的:

我试过更改 tintColorNSForegroundColorAttributeNameNSBackgroundColorAttributeName,但没有用。

对于检测到的链接的选定或突出显示颜色,没有记录 属性,但您应该能够通过重写委托方法 textView:shouldInteractWithURL:inRange: 并自行更改颜色来实现相同的效果。

来自 UITextViewDelegate 协议参考:

The text view calls this method if the user taps or long-presses the URL link. Implementation of this method is optional. By default, the text view opens the application responsible for handling the URL type and passes it the URL. You can use this method to trigger an alternative action, such as displaying the web content at the URL in a web view within the current application.

最后一个参数是一个名为 characterRange 的 NSRange 对象,它表示包含点击的 URL(或主题标签)的字符范围。使用该范围,您应该能够添加 NSForegroundColorAttributeName 等属性,以便仅更改被点击的特定主题标签的颜色。

您可能想要还原 touchesEndedtouchesCancelled 上的所有更改。

或者,您可以

可以解决这个问题,您可以使用 UIButton 而不是 textview。通过使用按钮,您可以获得相同的效果。

虽然没有publicAPI可以做到这一点,但我很好奇,还是决定去深挖private header for UITextField. I found that there is a class method on UITextField _sharedHighlightView which returns an instance of the private _UIHighlightViewclass。这是负责突出显示的class。调整 _sharedHighlightView 并更改其颜色将允许您更改任何检测到数据的链接的颜色:

警告:这是一个使用 method swizzling 和 private APIs/properties.

的 hack
class MyTextView: UITextView {

    var newHighlightView: AnyObject?

    func changeHighlight() {
        self.newHighlightView = UITextView.performSelector(Selector("_sharedHighlightView")).takeUnretainedValue()
        self.newHighlightView?.setValue(UIColor.redColor().colorWithAlphaComponent(0.6), forKey: "_color")

        let originalHighlightView = class_getClassMethod(MyTextView.self, Selector("_sharedHighlightView"))
        let newHighlightView = class_getClassMethod(MyTextView.self, #selector(MyTextView.swizzleHighlightView))
        method_exchangeImplementations(originalHighlightView, newHighlightView)
    }

    func swizzleHighlightView() -> AnyObject {
        return self.newHighlightView!
    }
}

在您的视图控制器中:

let textView = MyTextView(frame: CGRect(x: 0, y: 40.0, width: 200.0, height: 200.0))
textView.dataDetectorTypes = .All
textView.editable = false
textView.text = "Some text.  http://www.google.com/"
textView.changeHighlight()
self.view.addSubview(textView)

结果:

这可能会通过不强制展开任何可选值来进一步清理。