UITextView disabling text selection

后端 未结 11 1118
误落风尘
误落风尘 2020-12-08 00:19

I\'m having a hard time getting the UITextView to disable the selecting of the text.

I\'ve tried:

canCancelContentTouches = YES;
         


        
11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 01:11

    You can disable text selection by subclassing UITextView.

    The below solution is:

    • compatible with isScrollEnabled
    • compatible with loupe/magnifier
    • but not compatible with links (see here for a solution compatible with links)
    /// 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 {}
        }
    }
    

提交回复
热议问题