How to determine which textfield is active swift

前端 未结 7 1715
太阳男子
太阳男子 2020-12-06 04: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

7条回答
  •  失恋的感觉
    2020-12-06 04:51

    In order to improve @Reimond's answer 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

提交回复
热议问题