Disabling user input for UITextfield in swift

后端 未结 8 1013
半阙折子戏
半阙折子戏 2021-02-01 11:55

pretty trivial question, I know. But I can not find anything online.

I need to disable the user from being able to edit the text inside of a text field. So that when the

8条回答
  •  情书的邮戳
    2021-02-01 12:35

    I like to do it like old times. You just use a custom UITextField Class like this one:

    //
    //  ReadOnlyTextField.swift
    //  MediFormulas
    //
    //  Created by Oscar Rodriguez on 6/21/17.
    //  Copyright © 2017 Nica Code. All rights reserved.
    //
    
    import UIKit
    
    class ReadOnlyTextField: UITextField {
    
        /*
        // Only override draw() if you perform custom drawing.
        // An empty implementation adversely affects performance during animation.
        override func draw(_ rect: CGRect) {
            // Drawing code
        }
        */
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            // Avoid keyboard to show up
            self.inputView = UIView()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
    
            // Avoid keyboard to show up
            self.inputView = UIView()
        }
    
        override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
            // Avoid cut and paste option show up
            if (action == #selector(self.cut(_:))) {
                return false
            } else if (action == #selector(self.paste(_:))) {
                return false
            }
    
            return super.canPerformAction(action, withSender: sender)
        }
    
    }
    

提交回复
热议问题