首页 > 解决方案 > 如何在ios中TableviewCell中的uiTextField中实现日期

问题描述

我可以使用简单的文本字段成功选择日期,但如果是表格视图单元格中的文本字段,我会遇到问题并且无法选择日期。据我所知,我的操作方法 donePressed 无法正常工作能够在选择日期时在控制台中使用 dateformatter 打印日期。但我无法弄清楚如何在单元格中存在的文本字段中打印该日期。

 let datePicker = UIDatePicker()
    override func viewDidLoad() {
        super.viewDidLoad()
       tableView.reloadData()
        donePressed()
        //createDatePicker()
        // Do any additional setup after loading the view.
    }
    //Private function
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
        let toolBar = UIToolbar()
        toolBar.sizeToFit()
        let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed))
        cell.dateText.inputAccessoryView = toolBar
        cell.dateText.inputView = datePicker
        cell.dateText.text = "\(datePicker.date)"
        toolBar.setItems([doneBtn], animated: true)
        return cell
    }
    @objc func donePressed() {
        let cell1 = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
        cell1.dateText.text = "\(datePicker.date)"
        self.view.endEditing(true)
    }
   
   /* func createDatePicker()
    {
        let toolBar = UIToolbar()
        toolBar.sizeToFit()
        let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed))
        dateText.inputAccessoryView = toolBar
        dateText.inputView = datePicker
        toolBar.setItems([doneBtn], animated: true)
    }*/

标签: iosswiftdatepickertableview

解决方案


像这样更新选择器中的完成功能。

    @objc func donePressed() {
        let cell1 = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! TableViewCell
        cell1.dateText.text = "\(datePicker.date)"
        

self.view.endEditing(true)
}

您需要对单元格的引用,而出队不是为了获取对单元格的引用,而是将单元格出列以显示在表格视图中。


推荐阅读