Swift - UITextField完成輸入後關閉軟鍵盤

來源:互聯網
上載者:User

標籤:

總結了以下幾種方式,歡迎補充

 1,為空白地區綁定Touch Up Inside事件

 2,重寫touchesEnded方法

 3,為TextField綁定Did End On Exit事件

一、點擊編輯地區以外的地方時關閉(空白處地區綁定Touch Up Inside事件)

    建立一個項目,開啟Main.storyboard,添加一個Text Field,與ViewController建立串連,然後點擊空白處,在右邊視窗修改Custom Class 的class改為UIControl

     

   然後為UIControl綁定Touch Up Inside事件(只有改為UIControl後才能綁定事件)

   

  ViewController:

import UIKitclass 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();    }   }

二、點擊編輯地區以外的地方時關閉(重寫touchesEnded)

        只需要在ViewController裡重寫touchesEnded方法

//觸摸事件,當一個或多個手指離開螢幕時觸發    override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {        name.resignFirstResponder();    }

  

三、點擊軟鍵盤右下角的Done/Go/Next...關閉鍵盤(為TextField綁定Did End On Exit事件)

   選擇Main.storyboard中的Text Field,按住control拖拉的方式為其綁定Did End On Exit事件     

   

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

  

Swift - UITextField完成輸入後關閉軟鍵盤

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.