·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> Swift-UITextField完成输入后关闭软键盘的几种方法

Swift-UITextField完成输入后关闭软键盘的几种方法

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

总结了以下几种方式,欢迎补充

 1,为空白区域绑定Touch Up Inside事件

 2,重写touchesEnded方法

 3,为TextField绑定Did End On Exit事件

1,点击编辑区域以外的地方时关闭(空白处区域绑定Touch Up Inside事件

    新建一个项目,打开Main.storyboard,添加一个Text Field,与ViewController建立连接,然后点击空白处,在右边窗口修改Custom Class 的class改为UIControl

     

   然后为UIControl绑定Touch Up Inside事件(只有改为UIControl后才能绑定事件)

   

  ViewController:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var name: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
   
    @IBAction func CloseKeyBoard(sender: AnyObject) {
        name.resignFirstResponder();
    }
   
}

2,点击编辑区域以外的地方时关闭(重写touchesEnded)

        只需要在ViewController里重写touchesEnded方法

//触摸事件,当一个或多个手指离开屏幕时触发
    override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
        name.resignFirstResponder();
    }

  

3,点击软键盘右下角的Done/Go/Next...关闭键盘(为TextField绑定Did End On Exit事件)

   选择Main.storyboard中的Text Field,按住control拖拉的方式为其绑定Did End On Exit事件     

   

 @IBAction func DoneCloseKeyBoard(sender: AnyObject) {
        name.resignFirstResponder();
    }