问题描述
如何启用或禁用键盘返回键
我有两个TextFields
.
@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var textField2: UITextField!
-
textField1
具有 Next 按钮,如Return键;textField1
has the Next button like the Return Key;textField2
具有 Go 按钮,如Return键;textField2
has the Go button like the Return Key;我想启用第二个TextField的 Go 按钮,即使两个TextField都不为空.
I would like to enable the Go button of the second TextField just if both TextFields are not empty.
我尝试将
someTextField.enablesReturnKeyAutomatically
与TextFieldDelegate
一起使用,但是没有用.I tried to use
someTextField.enablesReturnKeyAutomatically
withTextFieldDelegate
, but did not work.感谢您的帮助.
推荐答案
下图:
textField2
被禁用,只要textField1
为空.如果后者为非空,则启用textField2
,但是仅当textField2
为非空(通过.enablesReturnKeyAutomatically
属性)时,启用Go
按钮Below:
textField2
is disabled as long astextField1
is empty. If the latter is non-empty, we enabletextField2
, but enable theGo
button only iftextField2
is non-empty (via.enablesReturnKeyAutomatically
property),/* ViewController.swift */ import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var textField1: UITextField! @IBOutlet weak var textField2: UITextField! override func viewDidLoad() { super.viewDidLoad() // text field delegates textField1.delegate = self textField2.delegate = self // set return key styles textField1.returnKeyType = UIReturnKeyType.Next textField2.returnKeyType = UIReturnKeyType.Go // only enable textField2 if textField1 is non-empty textField2.enabled = false // only enable 'go' key of textField2 if the field itself is non-empty textField2.enablesReturnKeyAutomatically = true } // UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { if (textField1.text?.isEmpty ?? true) { textField2.enabled = false textField.resignFirstResponder() } else if textField == textField1 { textField2.enabled = true textField2.becomeFirstResponder() } else { textField.resignFirstResponder() } return true } }
运行如下:
这篇关于如何在Swift中手动启用/禁用键盘Return键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!