在iOS Swift中实现月、日、时的自定义选择器可以通过使用UIPickerView来实现。以下是一个简单的示例代码:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var monthPicker: UIPickerView!
@IBOutlet weak var dayPicker: UIPickerView!
@IBOutlet weak var hourPicker: UIPickerView!
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
let days = Array(1...31)
let hours = Array(0...23)
override func viewDidLoad() {
super.viewDidLoad()
monthPicker.delegate = self
monthPicker.dataSource = self
dayPicker.delegate = self
dayPicker.dataSource = self
hourPicker.delegate = self
hourPicker.dataSource = self
}
// MARK: - UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == monthPicker {
return months.count
} else if pickerView == dayPicker {
return days.count
} else if pickerView == hourPicker {
return hours.count
}
return 0
}
// MARK: - UIPickerViewDelegate
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == monthPicker {
return months[row]
} else if pickerView == dayPicker {
return String(days[row])
} else if pickerView == hourPicker {
return String(hours[row])
}
return nil
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == monthPicker {
let selectedMonth = months[row]
print("Selected Month: \(selectedMonth)")
} else if pickerView == dayPicker {
let selectedDay = days[row]
print("Selected Day: \(selectedDay)")
} else if pickerView == hourPicker {
let selectedHour = hours[row]
print("Selected Hour: \(selectedHour)")
}
}
}
这个示例代码中,我们创建了三个UIPickerView,分别用于选择月、日和时。在viewDidLoad
方法中,我们将这三个选择器的delegate和dataSource设置为当前的ViewController。然后,我们实现了UIPickerViewDataSource
和UIPickerViewDelegate
协议中的方法来提供选择器的数据和处理选择事件。
在numberOfComponents(in pickerView: UIPickerView)
方法中,我们返回1,表示每个选择器只有一个组件。在pickerView(_:numberOfRowsInComponent:)
方法中,我们根据选择器的类型返回相应的数据数量。在pickerView(_:titleForRow:forComponent:)
方法中,我们根据选择器的类型返回相应的数据。在pickerView(_:didSelectRow:inComponent:)
方法中,我们根据选择器的类型处理选择事件,并打印所选的月、日和时。
这只是一个简单的示例,你可以根据自己的需求进行进一步的定制和美化。
领取专属 10元无门槛券
手把手带您无忧上云