Swift: One UITimePicker, Multiple Textfields

Deadly 提交于 2019-12-02 00:44:45

So If you only want to populate the currently selected textfield with the date provided, AND all of your textfields are located within your ViewController's MAIN view (or which ever view you specify, you just have to make sure that the view whose subviews you're looping throw contains your UITextFields), you could just check for whichever textfield is the first responder, and then add data to it, like this:

@objc
func timeValueChanged(_ sender: UIDatePicker) {
    let dateFormatter: DateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mm a"
    let date: String = dateFormatter.string(from: sender.date)

    if let textfield = view.subviews.first(where: { $0 is UITextField }) as? UITextView, textfield.isFirstResponder {
        textfield.text = date
    }
}

Also, you could potentially clean up your setup code with a similar method, like so:

setupTextFields() {

    for textfield in (view.subviews.map {$0 as? UITextField}.flatMap{$0}) {
        textfield.inputView = datePicker
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!