Enable copy and paste on UITextField without making it editable

后端 未结 6 2005
孤街浪徒
孤街浪徒 2020-11-27 17:54

I want the text in a UITextField (or ideally, a UILabel) to be non-editable, but at the same time give the user the ability to cop

6条回答
  •  Happy的楠姐
    2020-11-27 18:08

    This will do everything you need. Will be copyable. But not editable, and won't show a keyboard or a cursor.

    class ViewController: UIViewController {
    
        @IBOutlet weak var copyableUneditableTextfield: UITextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            copyableUneditableTextfield.delegate = self
            copyableUneditableTextfield.inputView = UIView()   //prevents keyboard     
            copyableUneditableTextfield.tintColor = .clear     //prevents cursor
            copyableUneditableTextfield.text = "Some Text You Want User To Copy But Not Edit"
    
        }
    
    }
    
    extension ViewController: UITextFieldDelegate {
    
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            return false //prevents editing
        }
    
    }
    

提交回复
热议问题