我在SwiftUI中创建了一个自定义时间选择器,用于输入所需的时间。该选择器通过将多个选择器并排放置来选择时间值,例如有一个用于小时、分钟、秒和毫秒的选择器。在iOS 14上,这个选择器工作得很好,但自从更新到iOS 15后,一次只能有一个选择器起作用。这似乎是因为选择器现在重叠了。对我来说,似乎设置框架没有正常工作,但我不确定如何解决这个问题。
代码由TimePickerClass组成,它存储时间选择器的值:
代码由TimePickerClass组成,它存储时间选择器的值:
class TimePickerClass: ObservableObject {
@Published var hoursTime = 0
@Published var secondsTime = 0
@Published var milisecondsTime = 0
@Published var minutesTime : Int = 0
func GetTime() -> Double {
return Double(hoursTime) * 3600.0 + Double(minutesTime) * 60.0 + Double(secondsTime) + Double(milisecondsTime)/100
}
func GetTimeString() -> String {
return TimeFormatted(timeInSeconds: GetTime())
}
func Reset(){
hoursTime = 0
secondsTime = 0
milisecondsTime = 0
minutesTime = 0
}
}
这是 TimePicker 视图
struct TimePicker: View {
@ObservedObject var viewModel : TimePickerClass
let pickerColor : Color = AppColor.PickerColors.backgroundColor
let textColor : Color = AppColor.PickerColors.textColor
let width :CGFloat = 30
var body: some View {
HStack
{
HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 0){
Spacer()
Picker("", selection: $viewModel.hoursTime) {
ForEach(0..<24){ hours in
if(hours < 10){
Text(" \(hours)").foregroundColor(textColor)
}
else{
Text("\(hours)").foregroundColor(textColor)
}
}
}.pickerStyle(WheelPickerStyle()).frame(width: width, height: 40).clipped().labelsHidden().clipShape(Rectangle())
Text(":").foregroundColor(textColor)
Picker("", selection: $viewModel.minutesTime) {
ForEach(0..<60){ minutes in
if(minutes < 10){
Text("0\(minutes)").foregroundColor(textColor)
}
else{
Text("\(minutes)").foregroundColor(textColor)
}
}
}.pickerStyle(WheelPickerStyle()).frame(width: width, height: 40).clipped().labelsHidden().clipShape(Rectangle())
Text(":").foregroundColor(textColor)
Picker("", selection: $viewModel.secondsTime) {
ForEach(0..<60){ seconds in
if(seconds < 10){
Text("0\(seconds)").foregroundColor(textColor)
}
else{
Text("\(seconds)").foregroundColor(textColor)
}
}
}.pickerStyle(WheelPickerStyle()).frame(width: width, height: 40).clipped().labelsHidden().clipShape(Rectangle())
Text(".").foregroundColor(textColor)
Picker("", selection: $viewModel.milisecondsTime) {
ForEach(0..<100){ miliSeconds in
if(miliSeconds < 10){
Text("0\(miliSeconds)").foregroundColor(textColor)
}
else{
Text("\(miliSeconds)").foregroundColor(textColor)
}
}
}.pickerStyle(WheelPickerStyle())
.labelsHidden()
.frame(width: width, height: 40)
.clipped()
.clipShape(Rectangle())
Spacer()
}.padding(.leading).padding(.trailing).overlay(RoundedRectangle(cornerRadius: 10).stroke(pickerColor, lineWidth: 2))
}.background(pickerColor.clipShape(RoundedRectangle(cornerRadius: 10))).overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.black, lineWidth: 1))
}
}
测试它的方法如下:
struct ContentView: View {
@ObservedObject var testTimePicker = TimePickerClass()
var body: some View {
VStack{
TimePicker(viewModel: testTimePicker)
Text("\(String(testTimePicker.GetTime()))")
Text(testTimePicker.GetTimeString())
}
}
iOS 14
iOS 15