SwiftUIで引数からViewを渡す。
struct TestView<Content: View>: View { let left: Content let right: Content init(left: Content, right: Content) { self.left = left self.right = right } var body: some View { GeometryReader { geometry in HStack() { left .frame(height: 50, alignment: .bottom) .background(Color.red) right .frame(height:50, alignment: .bottom) .background(Color.blue) } .frame(height:50, alignment: .bottom) } } } TestView( left: Text("100").customFont(size: 30), right: Text("kg").customFont(size: 20) ).frame(height: 40)
viewを囲って使
struct A: View { @State var isActive = false @State var number = Int.random(in: 1..<10).description var body: some View { NavigationView { Container { VStack { Button(action: { self.isActive.toggle() }) { Text("移動A\(number)") } NavigationLink(destination: B(),isActive: $isActive) { EmptyView() } } } }.navigationViewStyle(StackNavigationViewStyle()) } } struct Container <Content : View> : View { var content : Content @State var isLogin = false init(@ViewBuilder content: () -> Content) { self.content = content() } var body: some View { ZStack { Color.yellow.edgesIgnoringSafeArea(.all) VStack { VStack() { if isLogin { content } else { Text("ログインへ") } } } }.onAppear() { isLogin = false } } }
@Stateでdidset,WillSetは使える。
@State var form: Form = .none { didSet(oldValue) {} willSet(newValue) {} }