iOS学习四之UITextField

UITextField是iOS系统中进行文本输入操作的一种UI控件。

在ViewController的viewDidLoad中添加下面的方法即可

override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.     

        //设置输入框的大小

        let textField = UITextField(frame:CGRect(x:20,y:100,width:280,height:30))

       //设置输入框的style,none 无边框/line 线性风格/bezel bezel风格/roundedRect 边框风格

        textField.borderStyle = .roundedRect

       //提醒用户输入文字,用户输入时会不可见

        textField.placeholder = "Please input some words"

        //设置文字颜色

        textField.textColor = UIColor.cyan

        //设置文字大小

        textField.font = UIFont.systemFont(ofSize: 14)

        //设置文字对齐 left 居左/center 居中/right 居右

        textField.textAlignment = .left

       //设置输入框的图片

        let imageView = UIImageView(image:UIImage(named:"2"))

       //设置图片显示在文本框左侧,rightview也可以设置,实际操作中未设置成功 todo

        textField.leftView = imageView

       //图片显示的模式 never 从不/whileEditing 编辑时显示/unlessEditing 非编辑时显示/always 总是

        textField.leftViewMode = .unlessEditing

        //设置代理为自己,如果需要处理文本框中的文字的输入,需要设置代理

        textField.delegate = self

        self.view.addSubview(textField)

    }

   //代理方法,输入框中的内容将要改变时系统自动调用的回调方法

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string:String) -> Bool {

        if (string.count > 0) {

           //判断输入的是否时数字

            let charas:[Character] = ["0","1","2","3","4","5","6","7","8","9"]

            let char = string.first!

            if !charas.contains(char) {

                print("Please input number")

                return false

            }

            //判断输入是否超过11位

            if textField.text!.count+string.count > 11 {

                print("More than 11 digits")

            }

        }

        return true

    }

还有一些其他的代理方法,在不同的状况下,可以在不同的方法中加入处理

//输入框将要进入编辑模式时系统自动回调的方法

optional public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool

//输入框已经进入编辑模式时系统自动回调的方法

optional public func textFieldDidBeginEditing(_ textField: UITextField)

//输入框将要结束编辑模式时系统自动回调的方法

optional public func textFieldShoundEndEditing(_ textField: UITextField) -> Bool

//输入框已经结束编辑模式时系统自动回调的方法

optional public func textFieldDidEndEditing(_ textField: UITextField)

//输入框中的内容将要改变时系统自动回调的方法

optional public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

//输入框中的内容将要被清除时系统自动回调的方法

optional public func textFieldShouldReturn(_textField: UITextField) -> Bool

//用户按键盘上的return键后系统自动回调的方法

 

posted @ 2018-10-02 16:30  minminjy123  阅读(182)  评论(0编辑  收藏  举报