UITextField

UITextField 文本输入控件的使用

自定义UITextField样式

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let textField = UITextField(frame: CGRect(x: 30, y: 80, width: 260, height: 40))
        
        //文本框不同样式
        textField.borderStyle = UITextField.BorderStyle.roundedRect //圆角文本框
      /*
      .line 直角
      .none 没有边框
      */
        textField.placeholder = "Your Password" //默认文字
      
        textField.autocorrectionType = UITextAutocorrectionType.no //自动检查拼写错误
      
      // returnKey上显示样式,不对操作产生影响
        textField.returnKeyType = UIReturnKeyType.done
      /*
      done
      continue
      search
      */
      
        textField.clearButtonMode = UITextField.ViewMode.whileEditing // 清除按钮
      
        textField.keyboardType = UIKeyboardType.default //键盘类型
      /*
      .default
      .emailAddress
      .phonePad
      .numberPad
      */
        textField.keyboardAppearance = UIKeyboardAppearance.dark//键盘外观
      /*
      .dark
      .light
      */
      
      // 将输入的字符变成原点,密码输入
        textField.isSecureTextEntry = true
        
        let lock = UIImage(named: "lock")
        let lockView = UIImageView(image: lock)
        textField.leftView = lockView
        textField.leftViewMode = .always
        
        textField.delegate = self
        self.view.addSubview(textField)

    }
    
  // 按下 return 后执行的代理操作
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        
        return true
    }
    
}

响应UITextField的键盘通知

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    
    var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //创建一个textField
        textField = UITextField(frame: CGRect(x: 30, y: 480, width: 260, height: 30))
        textField.borderStyle = UITextField.BorderStyle.roundedRect
        textField.delegate = self
        self.view.addSubview(textField)
        
      //添加通知
      /*
      添加一个通知观察者, 对键盘willHide和willShow进行观察和监听
      */
        NotificationCenter.default.addObserver(self, selector: #selector(keyboradWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboradWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        
        return true
    }
    
    @objc func keyboradWillShow(_ Notification: Notification?) {
        
        textField.frame = CGRect(x: 30, y: 280, width: 260, height: 30)
    }
    
    @objc func keyboradWillHide(_ Notification: Notification?) {
        
        textField.frame = CGRect(x: 30, y: 480, width: 260, height: 30)
    }
    
}

你可能感兴趣的:(UITextField)