iPhone 版
ファイル構成
- ContentView.swift
- User.swift
- DetailView.swift
Code
User.swift
import Foundation
struct User: Identifiable {
let name: String
let bio: String
let id = UUID()
}
let users = [
User(name: "taro", bio: "I like sushi."),
User(name: "yuki", bio: "I like music."),
User(name: "mu", bio: "Software engineer")
]
DetailView.swift
import SwiftUI
struct DetailView: View {
let user: User
var body: some View {
VStack {
Text(user.name)
.font(.largeTitle)
.fontWeight(.bold)
Text(user.bio)
}
}
}
struct DetailView_Previews: PreviewProvider {
static var previews: some View {
DetailView(user: users[0])
}
}
ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
List(users) { user in
NavigationLink(destination: DetailView(user: user)) {
UserRow(user: user)
}
}
.navigationBarTitle("User list", displayMode: .inline)
}
}
}
struct UserRow: View {
let user: User
var body: some View {
VStack(alignment: .leading) {
Text(user.name)
Text(user.bio)
.font(.subheadline)
.foregroundColor(Color.gray)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
macOS 版
Code
ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
List(users) { user in
NavigationLink(destination: DetailView(user: user)) {
Text(user.name)
}
}.listStyle(SidebarListStyle())
}
}
}
struct DetailView: View {
let user: User
var body: some View {
VStack {
Text(user.name)
.font(.title)
.fontWeight(.bold)
Text(user.bio)
.foregroundColor(Color.gray)
}.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}