首页 > 解决方案 > 选择 DatePicker 后更新单元格中的日期(时间)

问题描述

我目前是一个应用程序,它具有允许用户添加时间表(时间)的功能

这是我到目前为止取得的进展
1. 添加了 textview 和 datepicker 并在点击 textView 后启用了 datepicker
2. 每个单元格上显示时间(我运行项目的时间)(如附图)

在日期选择器中选择时间后,我想在单元格中显示日期(如屏幕短时的晚上 10:10),但无法更新所选时间。
任何想法如何做到这一点?
提前致谢。

时间选择器视图控制器:

import UIKit

class TimeSelectorController: UICollectionViewController, 
UICollectionViewDelegateFlowLayout, UITextViewDelegate {

let cellId = "cellId"

let timeSelectorCell = TimeSelectorCell()


override func viewDidLoad() {
    super.viewDidLoad()

    collectionView.backgroundColor = .yellow

    collectionView.reloadData()
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "V", style: .plain, target: self, action: #selector(handleBack))

    collectionView.register(TimeSelectorCell.self, forCellWithReuseIdentifier: cellId)
}


@objc fileprivate func handleBack() {
    dismiss(animated: true, completion: nil)
}


override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 5
}


override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TimeSelectorCell

    cell.textView.inputView = timeSelectorCell.timePicker
    cell.textView.text = timeSelectorCell.handleSelectedTime()

    return cell
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: view.frame.width, height: 50)
   }

}

表选择器单元格:

import UIKit

class TimeSelectorCell: UICollectionViewCell {


let textView: UITextView = {
    let tv = UITextView()
    tv.text = "Time Goes Here"
    tv.isEditable = false
    return tv
}()

lazy var timePicker: UIDatePicker = {
    let picker = UIDatePicker()
    picker.datePickerMode = .time
    picker.minuteInterval = 10
    //picker.minuteInterval = 30
    picker.addTarget(self, action: #selector(handleSelectedTime), for: .valueChanged)
    return picker
}()

@objc func handleSelectedTime() -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm"
    let selectTime = dateFormatter.string(from: timePicker.date)

    textView.inputView = timePicker
    textView.text = selectTime

    print(selectTime)

    return selectTime
}


override init(frame: CGRect) {
    super.init(frame: frame)

    addSubview(textView)
    textView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, height: 0, width: 0)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
   }
 }

标签: iosswiftxcodedatepickertextview

解决方案


dateFormat将按照 12 小时格式获取时间

dateFormatter.dateFormat = "h:mm a"

推荐阅读