ios - 如何快速确定哪个文本字段处于事件状态

标签 ios swift

我无法确定哪个 UITextField 当前处于事件状态,因此如果他们在 UIBarButtonItem 上点击取消,我可以清除其文本。这是我的代码。有一个带有 UIPickerViewUIToolBar 和两个栏按钮项的 View 。取消项目有一个将清除其文本的操作,我不知道如何获得正确的 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 中将当前文本字段分配给它。 然后您可以在需要时调用此文本字段。

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")
   }
}

关于ios - 如何快速确定哪个文本字段处于事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30918732/

相关文章:

iphone - 在没有 UInavigationController 的情况下将 UIBarButtonItem 添加到 UINavigation 栏

iOS PushKit 响铃电话

ios - 如何读取录制的音频(二进制)文件以在 iOS 中上传

ios - 如何让 UIView 与底层 UIScrollView 对齐?

ios - 如何让手电筒闪烁?

ios - 如何使用 swift 在 firebase 中添加电话身份验证?

ios - Advent Of Code 第 14 天

xcode - Swift 中的 Playground 不会使用 Firebase

Swift - private var/func 与 private final var/func

ios - 位置权限弹出窗口不使用 CFBundleSpokenName