小编典典

如何确定哪个文本字段处于活动状态

swift

我无法弄清楚哪个UITextField当前处于活动状态,因此如果它们在上单击“取消”,则可以清除其文本UIBarButtonItem。这是我的代码。有一个视图UIPickerViewUIToolBar和两个栏按钮的项目。取消项的操作只能清除其文本,我无法弄清楚如何获得正确的文本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
}

阅读 266

收藏
2020-07-07

共1个答案

小编典典

您可以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")
   }
}
2020-07-07