我正在尝试使用 SwiftUI 实现分段控制。出于某种原因,分段选取器在单击它时不会在值之间切换。我经历了很多教程,但找不到与我的代码的任何区别:
struct MeetingLogin: View {
@State private var selectorIndex: Int = 0
init() {
UISegmentedControl.appearance().backgroundColor = UIColor(named: "JobsLightGreen")
UISegmentedControl.appearance().selectedSegmentTintColor = UIColor(named: "AlmostBlack")
UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white,
.font: UIFont(name: "OpenSans-Bold", size: 13)!],
for: .selected)
UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white,
.font: UIFont(name: "OpenSans-Regular", size: 13)!],
for: .normal)
}
var body: some View {
VStack {
...
Group {
Spacer().frame(minHeight: 8, maxHeight: 30)
Picker("video", selection: $selectorIndex) {
Text("Video On").tag(0)
Text("Video Off").tag(1)
}
.pickerStyle(SegmentedPickerStyle())
.padding([.leading, .trailing], 16)
Spacer().frame(minHeight: 8, maxHeight: 50)
Button(action: { self.sendPressed() }) {
ZStack {
RoundedRectangle(cornerRadius: 100)
Text("go")
.font(.custom("Roboto-Bold", size: 36))
.foregroundColor(Color("MeetingGreen"))
}
}
.foregroundColor(Color("MeetingLightGreen").opacity(0.45))
.frame(width: 137, height: 73)
}
Spacer()
}
}
}
将不胜感激任何建议!
最佳答案
更新:该问题似乎是由于 View
的重叠而发生的。是因为RoundedRectangle 的cornerRadius 值设置为100。将cornerRadius 的值设置为55 将恢复Picker
的功能。
该问题似乎是由 RoundedRectangle(cornerRadius: 100)
引起的内ZStack
.我没有解释为什么会发生这种情况。如果我找到了,我会添加原因。可能是 SwiftUI 错误。在我找到任何相关证据之前,我无法判断。所以这里是可以使 SegmentedControl
的代码工作没有任何问题。
struct MeetingLogin: View {
//...
@State private var selectorIndex: Int = 0
var body: some View {
VStack {
//...
Group {
Spacer().frame(minHeight: 8, maxHeight: 30)
Picker("video", selection: $selectorIndex) {
Text("Video On").tag(0)
Text("Video Off").tag(1)
}
.pickerStyle(SegmentedPickerStyle())
.padding([.leading, .trailing], 16)
Spacer().frame(minHeight: 8, maxHeight: 50)
Button(action: { self.sendPressed() }) {
ZStack {
RoundedRectangle(cornerRadius: 55)
Text("go")
.font(.custom("Roboto-Bold", size: 36))
.foregroundColor(Color("MeetingGreen"))
}
}
.foregroundColor(Color("MeetingLightGreen").opacity(0.45))
.frame(width: 137, height: 73)
}
Spacer()
}
}
}
关于SwiftUI 分段选取器在单击时不会切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62025772/