实现日期年月日的三级联动选择,可以创建一个包含三个列的UIPickerView。每个列分别表示年、月、日。根据用户的选择来动态更新每个列的数据。
首先,我们需要创建一个UIViewController,并在其上添加一个UIPickerView。然后,为每个列设置数据源和代理方法。
下面是一个简单的实现代码示例:
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var pickerView: UIPickerView!
let years = Array(1970...2021)
let months = Array(1...12)
let days = Array(1...31)
override func viewDidLoad() {
super.viewDidLoad()
pickerView.dataSource = self
pickerView.delegate = self
}
// MARK: - UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return years.count
} else if component == 1 {
return months.count
} else {
return days.count
}
}
// MARK: - UIPickerViewDelegate
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return String(years[row])
} else if component == 1 {
return String(months[row])
} else {
return String(days[row])
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let selectedYear = pickerView.selectedRow(inComponent: 0)
let selectedMonth = pickerView.selectedRow(inComponent: 1)
let selectedDay = pickerView.selectedRow(inComponent: 2)
let year = years[selectedYear]
let month = months[selectedMonth]
let day = days[selectedDay]
print("Selected date: \(year)-\(month)-\(day)")
}
}
这个示例中,我们创建了一个包含三个列的UIPickerView。每个列分别显示年、月和日的数据。用户选择日期时,我们通过UIPickerViewDelegate方法来获取所选值,并打印出来。
请注意,这只是一个简单的示例,你可以根据需要自定义UIPickerView的外观和行为。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: iOS开发Xcode5创建静态库详解