【发布时间】:2020-07-12 12:06:42
【问题描述】:
我正在尝试使用一些 Text 和 Picker 视图创建模型视图。选择器视图是有条件的,并且基于状态变量进行切换。切换工作正常,但我无法查看所选值。我正在使用简单的 Picker,无法看到选定的值
单击温度值时,所选值不显示任何内容。 有什么想法吗?
import SwiftUI
struct AddTemperature1: View {
@Environment(\.presentationMode) var presentationMode
@State var selection: String = ""
@State var selectedTemperature : String = ""
@State var showHideWheel: Bool = false
var body: some View {
VStack {
HStack {
Text("Temperature")
.foregroundColor(Color.gray)
.font(.custom("Heavy Condensed", size: 20))
.padding()
HStack{
Button(action: {
self.showHideWheel.toggle()
}){
Text(selectedTemperature.count > 0 ? selectedTemperature : "Select")
.foregroundColor(Color.cclBrandBlueColor)
.font(.custom("Heavy Condensed", size: 20))
//.padding()
Image(systemName: "chevron.right") .foregroundColor(Color.cclBrandBlueColor)
.padding(.trailing)
}
}
.frame(width: (UIScreen.main.bounds.width - 60) / 2, alignment: .trailing)
.padding()
}.background(Color("Color1"))
.cornerRadius(15)
.padding(\[.top, .bottom\],10)
.shadow(color: Color.black.opacity(0.1), radius: 5, x: 8, y: 8)
.shadow(color: Color.white.opacity(0.5), radius: 5, x: -8, y: -8)
Spacer()
if self.showHideWheel {
VStack (alignment: .center){
// VStack{
Picker(selection: $selection, label: Text("")){
ForEach(50...120, id:\.self){ i in
Text("\(i)").tag(i)
}
}.labelsHidden()
Text("You selected: \(selection)")
}.background(Color("Color1"))
.cornerRadius(25)
.frame(width: (UIScreen.main.bounds.width - 20), alignment: .center)
// .padding(\[.top, .bottom\],10)
.shadow(color: Color.black.opacity(0.1), radius: 5, x: 8, y: 8)
.shadow(color: Color.white.opacity(0.2), radius: 5, x: -8, y: -8)
}
}.frame(width: UIScreen.main.bounds.width)
.background(Image("background").resizable().scaledToFill().clipped())
}
}
struct AddTemperature1_Previews: PreviewProvider {
static var previews: some View {
AddTemperature1()
}
}]
【问题讨论】:
-
将包含选择器和文本的 VStack 移到它自己的视图中并预览/测试。基本上你的 AddTemperature1 视图太大了;你需要停止这样做,它使测试或开发 SwiftUI 变得不可能。您应该编写小视图。
-
我在视图之间有一些,它被删除了。但现在我简化了代码并删除了一些视图,但仍然无法从 Picker 中查看选定的值
-
我明白,我不是在给出答案,而是在指出一个坏习惯。对您不利,对 Stack Overflow 不利。您需要提供一个可验证的最小示例,而不是向我们展示您的全部观点。这与选择器的条件无关。将其简化为一个 Picker 和 Text,您会看到。
标签: ios xcode view swiftui picker