作者:无孔的鸟 | 来源:互联网 | 2024-12-17 09:10
本文将详细介绍如何封装一个多功能的PickerView组件,包括文本选择、日期选择和地理位置选择等功能,旨在提供一个更加灵活和易于使用的PickerView解决方案。
在之前的讨论中,我们已经对系统的PickerView进行了基础的介绍。虽然其使用方法相对简单,但若要创建一个功能全面且易于集成的PickerView类,则需要更多的设计与实现技巧。本文将分享我近期在一个项目中开发的PickerView类,该类不仅支持多种选择模式,还提供了简洁的API接口,便于开发者快速集成。
以下是该PickerView类的基本使用示例:
import UIKit
class ViewController: UIViewController {
private let textPicker: JHPickerView = {
var dataSource = [String]()
for i in 0..<20 {
dataSource.append("\(i)")
}
return JHPickerView(dataSource: dataSource, title: "单项选择")
}()
private let datePicker: JHPickerView = {
return JHPickerView(datePickerMode: .date, title: "日期选择")
}()
private let locationPicker: JHPickerView = {
return JHPickerView(areaType: .provinceCityDistrict, title: "地理位置选择")
}()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func textPickerButtonTapped(_ sender: UIButton) {
textPicker.show()
textPicker.selectRow(at: 3, animated: true)
textPicker.OnDoneSelection= { selectedRow, result in
print("Selected Row: \(selectedRow)")
print("Result: \(result)")
sender.setTitle(result, for: .normal)
}
textPicker.OnCancel= {
print("Picker dismissed")
}
}
@IBAction func datePickerButtonTapped(_ sender: UIButton) {
datePicker.show()
datePicker.setDate(Date(), animated: true)
datePicker.onDoneSelectionWithFormat("yyyy-MM-dd") { selectedDate, dateString in
print("Selected Date: \(selectedDate)")
print("Date String: \(dateString)")
sender.setTitle(dateString, for: .normal)
}
datePicker.OnCancel= {
print("Picker dismissed")
}
}
@IBAction func locationPickerButtonTapped(_ sender: UIButton) {
locationPicker.show()
locationPicker.OnDoneSelection= { province, city, district in
print("Province: \(province ?? "")")
print("City: \(city ?? "")")
print("District: \(district ?? "")")
sender.setTitle((province ?? "") + (city ?? "") + (district ?? ""), for: .normal)
}
locationPicker.OnCancel= {
print("Picker dismissed")
}
}
}
上述代码展示了如何通过初始化不同的参数来创建不同类型的PickerView,并通过闭包回调处理用户的选择结果。每个PickerView实例都提供了显示、选择特定项以及取消操作的方法,方便开发者根据实际需求进行调用。
完整代码及更多示例请参考代码链接。