SwiftUIのVStackのような複数のサブビューでビューを作成する方法
Aug 23 2020
基本的にモディファイアが適用されたVStackであるカスタムビューを作成しました。ただし、元のVStackビューとは異なり、複数のサブビューで使用する場合は、グループ化ビューを使用する必要があります。
以下の例の「グループ」を削除するにはどうすればよいですか?
import SwiftUI
struct ContentView: View {
var body: some View {
CustomGroup() {
Group {
Text("Hello")
Text("World")
}
}
}
}
struct CustomGroup<Content>: View where Content : View {
let content: () -> Content
var body: some View {
VStack() {
content()
}
.background(Color.yellow)
.cornerRadius(8)
}
}
回答
2 Asperi Aug 23 2020 at 11:59
ViewBuilderで初期化する必要があります
これが解決策です。Xcode 12 / iOS14でテスト済み
struct TestCustomGroup: View {
var body: some View {
CustomGroup {
Text("Hello")
Text("World")
}
}
}
struct CustomGroup<Content>: View where Content : View {
let content: () -> Content
init(@ViewBuilder _ content: @escaping () -> Content) {
self.content = content
}
var body: some View {
VStack {
content()
}
.background(Color.yellow)
.cornerRadius(8)
}
}