如何确定哪个文本字段是活跃的

时间:2022-10-22 16:45:01

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.

我无法弄清楚哪个UITextField当前处于活动状态,因此如果他们在UIBarButtonItem上点击取消,我可以清除它的文本。这是我的代码。有一个带有UIPickerView,UIToolBar和两个条形按钮项的视图。取消项目有一个动作,只会清除其文本我无法弄清楚如何获得正确的UITextField。

I've tried these both:

我试过这两个:

@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
}

And:

和:

@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
}

6 个解决方案

#1


31  

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.

您可以在类中声明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")
   }
}

#2


6  

In swift 4:

在快速4:

you can get the active UITextField like that

你可以像这样得到活跃的UITextField

extension UIView {
func getSelectedTextField() -> UITextField? {

    let totalTextFields = getTextFieldsInView(view: self)

    for textField in totalTextFields{
        if textField.isFirstResponder{
            return textField
        }
    }

    return nil

}

func getTextFieldsInView(view: UIView) -> [UITextField] {

    var totalTextFields = [UITextField]()

    for subview in view.subviews as [UIView] {
        if let textField = subview as? UITextField {
            totalTextFields += [textField]
        } else {
            totalTextFields += getTextFieldsInView(view: subview)
        }
    }

    return totalTextFields
}}

and then you call it like that

然后你就这样称呼它

let current = view.getSelectedTextField()

#3


0  

Use the delegate:

使用委托:

optional func textFieldDidEndEditing(_ textField: UITextField)

This will tell you when the active textfield finishes editing, and textField will contain a pointer to the one that's no longer going to be active.

这将告诉您活动文本字段何时完成编辑,textField将包含指向不再处于活动状态的指针。

#4


0  

/// Finds the textField that is the first responder in a view hierarchy
func findActiveTextField(in subviews: [UIView], textField: inout UITextField?) {

    guard textField == nil else { return }

    for view in subviews {
        if let tf = view as? UITextField, view.isFirstResponder {
            textField = tf
            break
        }
        else if !view.subviews.isEmpty {
            findActiveTextField(in: view.subviews, textField: &textField)
        }
    }
}

// Usage
var aView: UIView = UIView()
var activeField : UITextField?
findActiveTextField(in: aView.subviews, textField: &activeField)

#5


0  

I wrote a library to handle basic Form Creation Swift Pop Form. It doesn't use tags but rather sets a datasource that contains fields and uses indexPathForCell to query which is the active textfield. Check out the source code for more!

我写了一个库来处理基本的Form Creation Swift Pop Form。它不使用标记,而是设置包含字段的数据源,并使用indexPathForCell查询哪个是活动文本字段。查看源代码了解更多信息!

#6


0  

In order to improve @Reimond's answer Swift 4

为了提高@Reimond的答案Swift 4

extension UIView {
    var textFieldsInView: [UITextField] {
        return subviews
            .filter ({ !($0 is UITextField) })
            .reduce (( subviews.compactMap { $0 as? UITextField }), { summ, current in
                return summ + current.textFieldsInView
        })
    }
    var selectedTextField: UITextField? {
        return textFieldsInView.filter { $0.isFirstResponder }.first
    }
}

usage:

用法:

view.selectedTextField

view.selectedTextField

#1


31  

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.

您可以在类中声明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")
   }
}

#2


6  

In swift 4:

在快速4:

you can get the active UITextField like that

你可以像这样得到活跃的UITextField

extension UIView {
func getSelectedTextField() -> UITextField? {

    let totalTextFields = getTextFieldsInView(view: self)

    for textField in totalTextFields{
        if textField.isFirstResponder{
            return textField
        }
    }

    return nil

}

func getTextFieldsInView(view: UIView) -> [UITextField] {

    var totalTextFields = [UITextField]()

    for subview in view.subviews as [UIView] {
        if let textField = subview as? UITextField {
            totalTextFields += [textField]
        } else {
            totalTextFields += getTextFieldsInView(view: subview)
        }
    }

    return totalTextFields
}}

and then you call it like that

然后你就这样称呼它

let current = view.getSelectedTextField()

#3


0  

Use the delegate:

使用委托:

optional func textFieldDidEndEditing(_ textField: UITextField)

This will tell you when the active textfield finishes editing, and textField will contain a pointer to the one that's no longer going to be active.

这将告诉您活动文本字段何时完成编辑,textField将包含指向不再处于活动状态的指针。

#4


0  

/// Finds the textField that is the first responder in a view hierarchy
func findActiveTextField(in subviews: [UIView], textField: inout UITextField?) {

    guard textField == nil else { return }

    for view in subviews {
        if let tf = view as? UITextField, view.isFirstResponder {
            textField = tf
            break
        }
        else if !view.subviews.isEmpty {
            findActiveTextField(in: view.subviews, textField: &textField)
        }
    }
}

// Usage
var aView: UIView = UIView()
var activeField : UITextField?
findActiveTextField(in: aView.subviews, textField: &activeField)

#5


0  

I wrote a library to handle basic Form Creation Swift Pop Form. It doesn't use tags but rather sets a datasource that contains fields and uses indexPathForCell to query which is the active textfield. Check out the source code for more!

我写了一个库来处理基本的Form Creation Swift Pop Form。它不使用标记,而是设置包含字段的数据源,并使用indexPathForCell查询哪个是活动文本字段。查看源代码了解更多信息!

#6


0  

In order to improve @Reimond's answer Swift 4

为了提高@Reimond的答案Swift 4

extension UIView {
    var textFieldsInView: [UITextField] {
        return subviews
            .filter ({ !($0 is UITextField) })
            .reduce (( subviews.compactMap { $0 as? UITextField }), { summ, current in
                return summ + current.textFieldsInView
        })
    }
    var selectedTextField: UITextField? {
        return textFieldsInView.filter { $0.isFirstResponder }.first
    }
}

usage:

用法:

view.selectedTextField

view.selectedTextField