【Swift】- UITextField完成輸入后關閉軟鍵盤的幾種方法


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

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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM