はじめに
前回からの続きでSwiftUIのチュートリアル入門になります。
もと記事サイト

Building lists and navigation | Apple Developer Documentation
With the basic landmark detail view set up, you need to provide a way for users to see the full list of landmarks, and t...
Step0
このセクションでは、プレビューのサイズや複数のViewをまとめてプレビュー表示する方法を紹介します。
Step1
LandmarkRow.swift
のLandmarkRow_Previews
を変更していきます。LandmarkRow(landmark: landmarks[0])
のパラメータで指定されている要素番号を1に変更します。
import SwiftUI
struct LandmarkRow: View {
var landmark: Landmark
var body: some View {
HStack {
landmark.image
.resizable()
.frame(width: 50, height: 50)
Text(landmark.name)
Spacer()
}
}
}
struct LandmarkRow_Previews: PreviewProvider {
static var previews: some View {
LandmarkRow(landmark: landmarks[1])
}
}
プレビューの画像とテキストも自動で変更されます。

Step2
LandmarkRow
に対してpreviewLayout(_:)
を使用することで、プレビューのサイズを変更します。
import SwiftUI
struct LandmarkRow: View {
var landmark: Landmark
var body: some View {
HStack {
landmark.image
.resizable()
.frame(width: 50, height: 50)
Text(landmark.name)
Spacer()
}
}
}
struct LandmarkRow_Previews: PreviewProvider {
static var previews: some View {
LandmarkRow(landmark: landmarks[1])
.previewLayout(.fixed(width: 300, height: 70))
}
}
プレビューのサイズが指定した幅300、高さ70になりましたね!

Step3
次はGroup
を使用して、複数のViewをプレビュー表示させます。
複数のLandmarkRow
を記述したものを、Group
で囲みます。
import SwiftUI
struct LandmarkRow: View {
var landmark: Landmark
var body: some View {
HStack {
landmark.image
.resizable()
.frame(width: 50, height: 50)
Text(landmark.name)
Spacer()
}
}
}
struct LandmarkRow_Previews: PreviewProvider {
static var previews: some View {
Group {
LandmarkRow(landmark: landmarks[0])
.previewLayout(.fixed(width: 300, height: 70))
LandmarkRow(landmark: landmarks[1])
.previewLayout(.fixed(width: 300, height: 70))
}
}
}

Step4
Group
に対してpreviewLayout(_:)
を使用することで、子ビューすべてに設定を適用することができます。
import SwiftUI
struct LandmarkRow: View {
var landmark: Landmark
var body: some View {
HStack {
landmark.image
.resizable()
.frame(width: 50, height: 50)
Text(landmark.name)
Spacer()
}
}
}
struct LandmarkRow_Previews: PreviewProvider {
static var previews: some View {
Group {
LandmarkRow(landmark: landmarks[0])
LandmarkRow(landmark: landmarks[1])
}
.previewLayout(.fixed(width: 300, height: 70))
}
}
ちなみに、Group
を使用するもう一つの理由として、View単体での指定は10個までの制限があり、それ以上並べるとエラーが表示されます。これはVStack
やHStack
を使用した場合でも同じです。

Are there maximum limits to VStack?
I started with a clean project and added 5 buttons and 5 spacers in a VStack and all is good. When I add the 6th spacer ...
10個以上LandmarkRow
を並べるとエラーが表示されますね。

まとめ
プレビュー機能もいろいろ便利な機能が実装されているんですね。
このあたりの機能も知っていると、開発する際に便利かもしれないですね。
コメント