實現日期年月日的三級聯動選擇,可以創建一個包含三個列的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的外觀和行為。