簡體   English   中英

用swift編程語言隱藏文本字段的鍵盤

[英]hide keyboard for text field in swift programming language

我在Objective-C方面的經驗很少。 我想使用 Swift 編程語言隱藏文本字段的鍵盤。

我也試過這個

func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
    return true;
}

但是當我點擊返回時,該方法沒有被觸發。 有沒有人有這方面的運氣?

我認為問題在於設置委托。

請像這樣將 textfield Delegate 設置為您的 ViewController

class ViewController: UIViewController,UITextFieldDelegate {

然后像這樣為您的文本字段創建 IBOutlet

@IBOutlet var txtTest : UITextField = nil

確保它已連接到情節提要中視圖上的文本字段。

最后使用

txtTest.delegate=self

我們快完成了。 現在將此委托函數放入您的類中。

func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
    {
        textField.resignFirstResponder()
        return true;
    }

希望這能解決您的問題。

只需覆蓋名為“touchesBegan”的 UIViewController 方法並將 endEditing 設置為 true。 像這樣:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
    self.view.endEditing(true)
}

為了在按下按鈕時隱藏鍵盤,您需要使用以下功能。

self.view.endEditing(true)

這在按下按鈕時起作用。

希望這可以幫助那里的人。

開始了:

  1. 將 textField 添加到您的視圖
  2. 創建一個新的 Swift 文件
  3. 將此新文件設置為該特定視圖的類
  4. 將 TextField 添加到您的視圖
  5. 為文本字段創建一個出口(我的名為“txtField”!)
  6. 將 Swift 類文件中的任何代碼替換為:

     import Foundation import UIKit //01 create delegation class MyViewController2: UIViewController,UITextFieldDelegate { @IBOutlet weak var txtField: UITextField!=nil override func viewDidLoad() { super.viewDidLoad() // additional setup after loading the view //02 set delegate to textfield txtField.delegate = self } //03 textfield func for the return key func textFieldShouldReturn(textField: UITextField) -> Bool { txtField.resignFirstResponder() return true; } //textfield func for the touch on BG override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { txtField.resignFirstResponder() self.view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() //dispose of any resources that can be recreated } }
    1. 試試看,開心並說聲謝謝!

現在在 Swift 3/4/5 中,最簡單的方法是

方法 1:在按下 'return' 鍵時調用。

func textFieldShouldReturn(_ textField: UITextField) -> Bool 
 {
 textField1.resignFirstResponder()
 textField2.resignFirstResponder()
        return true;
    }

方法 2:在按下 'return' 鍵時調用。

func textFieldShouldReturn(_ textField: UITextField) -> Bool 
    {
    self.view.endEditing(true)
        return true;
    }

方法 3:全局方法寫入視圖確實加載

self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))

注意:不要忘記添加這個。 否則它不起作用。

UIGestureRecognizerDelegate, UITextFieldDelegate

我希望它對你有用:)

以簡單的方式隱藏鍵盤只需覆蓋 UIView“touchBegan 方法”。 因此,當您點擊視圖中鍵盤隱藏的任何位置時。 這是示例代碼..(Swift 3.0 更新代碼)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
{
   self.view.endEditing(true)
}

就像@spfursich 所說的那樣,最好的方法是,當用戶觸摸鍵盤上方的任何位置時,鍵盤就會消失。 這是代碼:

override func viewDidLoad() {
    super.viewDidLoad()

    var tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
    self.view.addGestureRecognizer(tap)
}

func DismissKeyboard(){
    self.view.endEditing(true)
}
  • 將 UITextFieldDelegate 添加到類聲明中:

    類 ViewController: UIViewController, UITextFieldDelegate

  • 連接文本字段或以編程方式編寫

    @IBOutlet 弱變量 userText:UITextField!

  • 將您的視圖控制器設置為視圖中的文本字段委托加載:

     override func viewDidLoad() { super.viewDidLoad() self.userText.delegate = self }
  • 添加以下功能

    func textFieldShouldReturn(userText: UITextField!) -> Bool { userText.resignFirstResponder() return true; }

    有了所有這些,您的鍵盤將通過觸摸文本字段外部以及按返回鍵開始關閉。

UIApplication.sharedApplication().sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, forEvent:nil)

首先,您需要為文本字段設置delegate ,然后您需要包含resignFirstResponder()以在按下鍵盤的返回按鈕時隱藏鍵盤。

 func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
 {
   textField .resignFirstResponder()
   return true;
 }

您可以嘗試使用此代碼讓“返回”鍵執行代碼。

func textFieldShouldReturn(textField: UITextField) -> Bool{
    textField.resignFirstResponder()
    performAction()
    return true;
}

func performAction(){

//execute code for your action inside this function

}

希望這可以幫到你。

您也可以這樣做:從 TextField 的連接檢查器添加事件“Did end on exit”,並將其連接到相關 ViewController 的方法

在我的示例中,我將其連接到名為“已結束”的方法

將 sender 聲明為 UITextField,然后調用 sender.resignFirstResponder(); 像這樣:

@IBAction func ended (sender: UITextField){ sender.resignFirstResponder(); }

在這里我已經解決了這個問題,當鍵盤打開並且視圖隱藏在鍵盤后面時......那個時候我們需要動態更改 UI 約束以使整個視圖可見。 就我而言,我正在動態更改UITextField的 bottonConstraint。

所以,這里是完整的代碼。 我在UIViewController上有一個UITextViewUITextField用於測試...

import UIKit

class ViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate {

    @IBOutlet weak var textView: UITextField!

    @IBOutlet weak var textField: UITextView!

      /*Height Constraint for textField*/
    @IBOutlet weak var bottom: NSLayoutConstraint!

    var defaultHeight:CGFloat = 0.0;

    override func viewDidLoad() {
        super.viewDidLoad()

        defaultHeight = bottom.constant;

        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);


        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);

    }

    override func resignFirstResponder() -> Bool {
        textView.resignFirstResponder();
        textField.resignFirstResponder();
        return true;
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        resignFirstResponder()
        print("touched began")
    }

    func textViewDidEndEditing(textView: UITextView) {
        resignFirstResponder()
        print("text view did end editing")
    }

    func textViewShouldEndEditing(textView: UITextView) -> Bool {
        resignFirstResponder()
        print("text view should end editing")
        return true;
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        print("text field should return")
        resignFirstResponder()
        return true;
    }

    func textFieldDidEndEditing(textField: UITextField) {
        resignFirstResponder()
        print("did end editing")
    }

    func keyboardWillShow(notification: NSNotification) {
        print("keyboard will show.............")
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            let a = keyboardSize.height;
            self.bottom.constant = a + defaultHeight;
            self.view.updateConstraints();
        }
    }

    func keyboardWillHide(nofication:NSNotification)
    {
        print("keyboard will hide................")
        bottom.constant = defaultHeight;
        self.view.updateConstraints();

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

當您調用 UIAlertController 時,如果您想隱藏鍵盤,請在完成處理程序中放置條件。

self.present('nameOfYourUIAlertController', animated: true, completion: {
    if condition == true {
        'nameOfYourUIAlertController'.textFields![0].resignFirstResponder()
    }
})

這對我很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM