您可以通过子类化来禁用文本选择UITextView
。
下面的解决方案是:
/// Class to disallow text selection
/// while keeping support for loupe/magnifier and scrolling
/// https://stackoverflow.com/a/49428248/1033581
class UnselectableTextView: UITextView {
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
// prevents selection from loupe/magnifier (_UITextSelectionForceGesture), multi tap, tap and a half, etc.
// without losing the loupe/magnifier or scrolling
// but we lose taps on links
addSubview(transparentOverlayView)
}
let transparentOverlayView: UIView = {
$0.backgroundColor = .clear
$0.autoresizingMask = [.flexibleHeight, .flexibleWidth]
return $0
}(UIView())
override var contentSize: CGSize {
didSet {
transparentOverlayView.frame = CGRect(origin: .zero, size: contentSize)
}
}
// required to prevent blue background selection from any situation
override var selectedTextRange: UITextRange? {
get { return nil }
set {}
}
}