我有一个简单的注册表格,当用户按下时Continue Button
,如果他们没有输入任何字段,我会显示一个弹出窗口。
struct ContentView: View {
@State var firstName = ""
@State var lastName = ""
@State private var validationMessage = ""
@State private var showValidationMessage = false
private var isFormValid: Bool {
!firstName.isEmpty &&
!lastName.isEmpty
}
private func checkGeneralFormCompletion() {
if isFormValid {
showValidationMessage = false
} else {
let errorText = {
if firstName.isEmpty {
return "First name empty"
} else if lastName.isEmpty {
return "Last name empty"
} else {
return ""
}
}()
validationMessage = errorText
showValidationMessage = !errorText.isEmpty
}
}
var body: some View {
VStack(spacing: 12) {
let _ = Self._printChanges()
TextField("First Name", text: $firstName)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.bottom, 10)
TextField("Last Name", text: $lastName)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.bottom, 10)
Button(action: {
checkGeneralFormCompletion()
}) {
Text("Continue")
.foregroundColor(.white)
.padding(.horizontal, 45)
.padding([.top, .bottom], 10)
.background( Color.red)
.cornerRadius(5)
}
.popover(isPresented: self.$showValidationMessage,
attachmentAnchor: .point(.top),
arrowEdge: .top,
content: { [validationMessage] in
let _ = print("validationMessage :: popover :: ", validationMessage)
VStack {
Text(validationMessage)
}
.multilineTextAlignment(.center)
.lineLimit(0)
.foregroundStyle(.black)
.font(.system(size: 18, weight: .semibold, design: .rounded))
.padding()
.presentationCompactAdaptation(.none)
.fixedSize(horizontal: false, vertical: true)
.frame(minWidth: 200)
})
.padding(.top, 70)
}
.padding()
// .onChange(of: validationMessage) { oldValue, newValue in
// print("CHANGE text VALIDATE MSG")
// }
// .onChange(of: showValidationMessage) { oldValue, newValue in
// print("CHANGE VALIDATE MSG")
// }
}
}
如果我注释掉强捕获[validationMessage] in
,当用户第一次按下按钮时,弹出窗口将显示空文本并且body
不会重新渲染(基于调用)。但是如果我为of_printChanges
提供强捕获或添加修饰符,则主体将重新渲染并且弹出窗口将显示正确的文本。closure
.popover
.onChange
VStack
我的问题是,为什么当我提供 的强捕获时@State
,它会导致body
重新渲染?任何见解或建议都将不胜感激!