【发布时间】:2018-08-27 04:37:36
【问题描述】:
我目前是一个具有允许用户添加时间表(时间)功能的应用
这是我目前取得的进展
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")
}
}
【问题讨论】:
标签: ios swift xcode datepicker textview