SwiftUI 分段选取器在单击它时不会切换



我正在尝试使用 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的重叠而发生的,因为圆角矩形的角半径值设置为 100。将角半径的值提高到55将恢复Picker的功能。

该问题似乎是由于ZStack内部的RoundedRectangle(cornerRadius: 100)引起的。我没有解释为什么会发生这种情况。如果我发现,我会添加原因。可能是 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()
}
}
}

Xcode 12 iOS 14 您可以通过在分段控件(选取器(的点击手势上添加 if-else 条件来获取它

@State private var profileSegmentIndex = 0
Picker(selection: self.$profileSegmentIndex, label: Text("Jamaica")) {
Text("My Posts").tag(0)

Text("Favorites").tag(1)
}
.onTapGesture {
if self.profileSegmentIndex == 0 {
self.profileSegmentIndex = 1
} else {
self.profileSegmentIndex = 0
}
}
.pickerStyle(SegmentedPickerStyle())
.padding()

如果您需要将其用于 2 个以上的段,您可以尝试使用枚举:)

你的代码/视图缺少 if 条件,无法知道当选择器索引为 0 或 1 时会发生什么。

它必须看起来像这样:

var body: some View {
VStack {
if selectorIndex == 0 {
//....Your VideoOn-View 
} else {
//Your VideoOff-View
}
}

最新更新