Swift:一个UITimePicker,多个Textfields

时间:2017-11-17 20:01:01

标签: ios swift uidatepicker

我有一个只有时间的TextFields变量。我希望能够将不同的时间设置为不同的*@IBOutlets for all the UITextFields...* private var datePicker = UIDatePicker() override func viewDidLoad() { super.viewDidLoad() self.setupDatePicker() self.setupTextFields() } func setupDatePicker() { self.datePicker.frame = CGRect(x: 0, y: 50, width: self.view.frame.width, height: 200) self.datePicker.timeZone = NSTimeZone.local self.datePicker.datePickerMode = .time self.datePicker.minuteInterval = 30 self.datePicker.backgroundColor = .white self.datePicker.addTarget(self, action: #selector(self.timeValueChanged(_:)), for: .valueChanged) } func setupTextFields() { self.mondayOpenTF.inputView = self.datePicker self.mondayCloseTF.inputView = self.datePicker self.tuesdayOpenTF.inputView = self.datePicker self.tuesdayCloseTF.inputView = self.datePicker self.wednesdayOpenTF.inputView = self.datePicker self.wednesdayCloseTF.inputView = self.datePicker self.thursdayOpenTF.inputView = self.datePicker self.thursdayCloseTF.inputView = self.datePicker self.fridayOpenTF.inputView = self.datePicker self.fridayCloseTF.inputView = self.datePicker self.saturdayOpenTF.inputView = self.datePicker self.saturdayCloseTF.inputView = self.datePicker self.sundayOpenTF.inputView = self.datePicker self.sundayCloseTF.inputView = self.datePicker } @objc func timeValueChanged(_ sender: UIDatePicker) { let dateFormatter: DateFormatter = DateFormatter() dateFormatter.dateFormat = "h:mm a" let date: String = dateFormatter.string(from: sender.date) self.mondayOpenTF.text = date as String self.mondayCloseTF.text = date as String self.tuesdayOpenTF.text = date as String self.tuesdayCloseTF.text = date as String self.wednesdayOpenTF.text = date as String self.wednesdayCloseTF.text = date as String self.thursdayOpenTF.text = date as String self.thursdayCloseTF.text = date as String self.fridayOpenTF.text = date as String self.fridayCloseTF.text = date as String self.saturdayOpenTF.text = date as String self.saturdayCloseTF.text = date as String self.sundayOpenTF.text = date as String self.sundayCloseTF.text = date as String } 。我设置它的方式是,当我改变一次时,它们都会改变。

代码:

UIDatePicker

是否可以让一个qos/device-qos-range单独管理,或者我是否必须为每个文本字段创建14个不同的填充文件?

1 个答案:

答案 0 :(得分:2)

因此,如果您只想使用提供的日期填充当前选定的文本字段,并且所有文本字段都位于ViewController的 MAIN 视图中(或者哪个视图中)你指定,你只需要确保你的循环抛出的子视图包含你的UITextField s的视图,你可以检查第一个响应者的哪个文本字段,然后向它添加数据,就像这样:

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

此外,您可以使用类似的方法清理设置代码,如下所示:

setupTextFields() {

    for textfield in (view.subviews.map {$0 as? UITextField}.flatMap{$0}) {
        textfield.inputView = datePicker
    }
}