- By刘立博
- 2021-09-21 22:10:54
- 2782人已阅读
一个栗子: 最简单的DatePicker
首先定义一个属性,用来存储格式化后的日期
@State var selectedDate: String = ""
定义一个Binding对象,通过其set方法,在用户选择日期后,格式化日期并存储与上面定义个属性中
var bindingDate : Binding<Date>
{
Binding<Date>(
get: {
Date()
}, set: {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
selectedDate = formatter.string(from: $0)
})
}
添加一个DatePicker视图,将他和bindingDate属性进行绑定,并设置DatePicker的组件类型为日期类型,即只显示年月日的选择界面
DatePicker(
selection: bindingDate,
displayedComponents: [.date]
){
Text("\(selectedDate)")
}
至此,DatePicker组件已出现在屏幕上,点击之后弹出日期选择浮层,选择日期后,格式化后的日期将显示在左侧
约束可选日期
通过定义一个日期范围可以约束可选日期,假定为前1天,后5天
var limitRange: ClosedRange<Date> {
let oneDaysAgo = Calendar.current.date(byAdding: .day, value: -1, to: Date())!
let fiveDaysFromNow = Calendar.current.date(byAdding: .day, value: 5, to: Date())!
return oneDaysAgo...fiveDaysFromNow
}
在DatePicker中传入设置
DatePicker(
selection: bindingDate,
in: limitRange,
displayedComponents: [.date]
){
Text("\(selectedDate)")
}
拾取器样式: datePickerStyle
DatePicker提供了4种选择器样式供我们选择,通过下列代码进行设置
DatePicker(
selection: bindingDate,
displayedComponents: [.date]
){
Text("\(selectedDate)")
}.datePickerStyle(DefaultDatePickerStyle())
DefaultDatePickerStyle (iOS, macOS)
默认的DatePicker样式
WheelDatePickerStyle (iOS)
GraphicalDatePickerStyle (iOS)
StepperFieldDatePickerStyle (macOS)
FieldDatePickerStyle (macOS)
macOS专属样式,略
文字色
通过accentColor可以设置文字颜色
DatePicker(
selection: bindingDate,
displayedComponents: [.date]
){
Text("\(selectedDate)")
}
.datePickerStyle(DefaultDatePickerStyle())
.accentColor(.orange)
背景色
通过background可以设置拾取器背景色
DatePicker(
selection: bindingDate,
displayedComponents: [.date]
){
Text("\(selectedDate)")
}
.datePickerStyle(DefaultDatePickerStyle())
.accentColor(.orange)
.background(Color.blue)