故事板日期选择器中的选择性日期(iOS 开发)
Posted
技术标签:
【中文标题】故事板日期选择器中的选择性日期(iOS 开发)【英文标题】:Selective dates in Date Picker for Storyboard (iOS Development) 【发布时间】:2021-07-17 10:11:57 【问题描述】:是否可以在 ios 故事板中将 DatePicker 限制为具有给定范围的选择性日期? 我正在尝试让 DatePicker 仅在星期六显示。
【问题讨论】:
也许您需要创建自定义日历。 【参考方案1】:您无法在 Storyboard 中执行此操作,也无法使用 UIDatePicker
...
但是,使用UIPickerView
非常简单。
这是一个简单的例子:
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate
let picker = UIPickerView()
let dateFormatter = DateFormatter()
var thisSaturday: Date!
override func viewDidLoad()
super.viewDidLoad()
// set your desired date format
dateFormatter.dateStyle = .medium
picker.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(picker)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// center picker view with default width and height
picker.centerXAnchor.constraint(equalTo: g.centerXAnchor),
picker.centerYAnchor.constraint(equalTo: g.centerYAnchor),
])
picker.dataSource = self
picker.delegate = self
// get the date for the "upcoming Saturday"
let today = Date()
let daysToAdd = 7 - (Calendar.current.dateComponents([.weekday], from: today).weekday ?? 0 )
guard let d = Calendar.current.date(byAdding: .day, value: daysToAdd, to: today) else
fatalError("Could not get a valid date!!! (This should never happen...)")
thisSaturday = d
func numberOfComponents(in pickerView: UIPickerView) -> Int
return 1
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
// how many weeks in the future do you want to allow?
// for example, 52-weeks x 4-years
return 52 * 4
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
// each row will be
// "upcoming Saturday" plus
// 7-days x row number
guard let d = Calendar.current.date(byAdding: .day, value: 7 * row, to: thisSaturday) else
fatalError("Could not get a valid date!!! (This should never happen...)")
return dateFormatter.string(from: d)
【讨论】:
以上是关于故事板日期选择器中的选择性日期(iOS 开发)的主要内容,如果未能解决你的问题,请参考以下文章