问题
I have a view BugSplitView
which works fine alone but causes a
precondition failure: attribute failed to set an initial value
error when navigated to in either preview or the simulator.
The view has an upper part (Color) and a lower part (Color) separated by a horizontal button bar and laid out using the GeometeryReader and a split
state. When it is the destination of NavigationButton it doesn't show properly in the Preview and reports the assertion above when run in the simulator. Remove the BugButtonBar
and it works. Got me stumped! Help.
import SwiftUI
struct BugSplitView: View {
@State var split : CGFloat = 0.75
var buttons : [BugButtonBar.Info]{
[BugButtonBar.Info(title: "title", imageName: "text.insert"){}]
}
var body: some View {
GeometryReader{ g in
VStack(spacing: 0){
Color.gray
.frame(width: g.size.width, height: (g.size.height) * self.split)
VStack{
BugButtonBar(infos: self.buttons)
Color(white: 0.3)
}
.frame(height: (g.size.height) * (1 - self.split))
}
}.edgesIgnoringSafeArea(.all)
}
}
struct BugButtonBar : View{
struct Info : Identifiable {
var id = UUID()
var title : String
var imageName : String
var action: () -> Void
}
var infos : [Info]
func color() -> Color{
Color.black
}
var body: some View {
HStack(){
Spacer()
ForEach(self.infos){ info in
Button(action: info.action){
Text(info.title)
}
Spacer()
}
}
}
}
struct ShowBugView : View{
var body : some View{
NavigationView {
NavigationLink(destination: BugSplitView()){
Text("Show Bug")
}
}
}
}
struct BugSplitView_Previews: PreviewProvider {
static var previews: some View {
Group{
BugSplitView()
ShowBugView()
}
}
}
回答1:
The problem is that your buttons are declared as computed property. To solve the crash declare them like this:
var buttons = [BugButtonBar.Info(title: "title", imageName: "text.insert"){}]
回答2:
Turns out the id property of struct Info was the problem. Changed it to a computed property as follows:
var id : String {
title + imageName
}
Great example of why I love/hate SwiftUI.
来源:https://stackoverflow.com/questions/58573640/runtime-error-precondition-failure-attribute-failed-to-set-an-initial-value