View部品を作れるようになると、多様なレイアウトを含むことができるようになります。たとえば前回作ったリストより大きな画像サムネイルで主張したいリストがあるとします。今回は食べ物写真が映えるように FoodAndDrinkRow という名前の新しいView部品を追加します。
- 
前回のコードに続けて書く
 
- 
View部品にするswiftファイルを追加する
- ファイルリストで右クリック, New Fileを選択して新しいファイルを作る
 
- File.swiftを FoodAndDrinkRow.swift に変更する
 
 
- FoodAndDrinkRowを以下のように記述する
- 受け取る値は imageName, title, message の3つ
 
- VStackで縦方向に並べる
- alignment:.leading をつけて左寄せに
 
 
 
コード1#
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  | 
import SwiftUI
struct FoodAndDrinkRow : View {
    var imageName: String
    var title: String
    var message: String
    
    var body: some View {
        VStack( alignment:.leading ) {
            Image( imageName )
            .resizable()
            .scaledToFit()
            .frame( maxHeight:200 )
            
            Text( title )
            .font( .system( size:20.0 ) )
            .padding( .bottom, 10 )
            
            Text( message )
            .font( .system( size:14.0 ) )
            .foregroundStyle( .secondary )
        }
        .padding( .vertical, 10.0 )
    }
}
  | 
 
ContentViewで、作成したFoodAndDrinkRowを使ってみます。
- List内に Section(“食べ物画像”) を追加
- Sectio内に FoodAndDrinkRow を4つ書く
 
 
コード2#
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  | 
import SwiftUI
struct ContentView: View {
    var body: some View {
        List {
            Section( "景色画像" ) {
                SceneryRow( imageName:"CC0_01", title:"景色1" )
                SceneryRow( imageName:"CC0_04", title:"景色2" )
                SceneryRow( imageName:"CC0_06", title:"景色3" )
                SceneryRow( imageName:"CC0_07", title:"景色4" )
                SceneryRow( imageName:"CC0_10", title:"景色5" )
            }
            
            Section( "食べ物画像" ) {
                FoodAndDrinkRow( 
                    imageName:"CC0_05", title: "ハンバーガーセット", message: "おいしいです"
                )
                FoodAndDrinkRow( 
                    imageName:"CC0_08", title: "カフェラテ", message: "おちつきます"
                )
                FoodAndDrinkRow( 
                    imageName:"CC0_09", title: "ケーキ", message: "あまいです"
                )
                FoodAndDrinkRow( 
                    imageName:"CC0_12", title: "お酒", message: "酔います"
                )
            }
        }
        .listStyle( .grouped )
    }
}
  | 
 
景色画像より大きな画像の食べ物画像リストが表示されます。