如何确定哪个文本字段是活跃的 [英] How to determine which textfield is active swift
问题描述
我无法弄清楚哪个 UITextField
当前有效,所以如果他们在 UIBarButtonItem
。这是我的代码。有一个带有 UIPickerView
, UIToolBar
和两个条形按钮项的视图。取消项目有一个动作,只会清除其文本我无法弄清楚如何获得正确的 UITextField
。
I cant figure out which UITextField
is currently active so i can clear its text if they hit cancel on a UIBarButtonItem
. Here is my code. There is a view with a UIPickerView
,UIToolBar
and two bar button items. The cancel item has an action that will clear its text only i cant figure out how to get the correct UITextField
.
我试过这两个:
@IBAction func cancelText(sender: AnyObject) {
if self.truckYear.editing == true{
println("truckYear")
clearText(self.truckYear)
} else if self.truckMake.editing == true{
clearText(self.truckMake)
}
}
@IBAction func doneText(sender: AnyObject) {
pickerView.hidden = true
}
func clearText(textField:UITextField){
println("in clear text")
textField.text = nil
}
并且:
@IBAction func cancelText(sender: AnyObject) {
if self.truckYear.isFirstResponder(){
println("truckYear")
clearText(self.truckYear)
} else if self.truckMake.isFirstResponder(){
clearText(self.truckMake)
}
}
@IBAction func doneText(sender: AnyObject) {
pickerView.hidden = true
}
func clearText(textField:UITextField){
println("in clear text")
textField.text = nil
}
推荐答案
您可以在类中声明 UITextField
属性,并在 textFieldDidBeginEditing <中为其指定当前文本字段/ code>。
然后你可以随时调用这个文本字段。
You can declare a UITextField
property in your class, and assign the current text field to it in textFieldDidBeginEditing
.
Then you can just call this text field whenever you need to.
class ViewController : UIViewController, UITextFieldDelegate {
var activeTextField = UITextField()
// Assign the newly active text field to your activeTextField variable
func textFieldDidBeginEditing(textField: UITextField) {
self.activeTextField = textField
}
// Call activeTextField whenever you need to
func anotherMethod() {
// self.activeTextField.text is an optional, we safely unwrap it here
if let activeTextFieldText = self.activeTextField.text {
print("Active text field's text: \(activeTextFieldText)")
return;
}
print("Active text field is empty")
}
}
这篇关于如何确定哪个文本字段是活跃的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!