2020.8.8
GeometryReaderを使用して画面に合わせて画像のサイズを変更する
Resizing images to fit the screen using GeometryReader
struct ContentView: View {
var body: some View {
/*
VStack {
Image("IMG_1308")
//.frame(width: 300, height: 300)
//.clipped()
//---------
.resizable()
//.aspectRatio(contentMode: .fill)
.aspectRatio(contentMode: .fit)
.frame(width: 300, height: 300)
}
*/
VStack {
GeometryReader { geo in
Image("IMG_1247")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: geo.size.width)
}
}
}
}
ScrollViewでデータをスクロールする方法
How ScrollView lets us work with scrolling data
ScrollView:注意が必要な重要な注意点があります。スクロールビューにビューを追加すると、すぐに作成されます。
List:When that code runs you’ll see it acts lazily: it creates instances of only when really needed.
import SwiftUI
//----------------------
struct CustomText: View {
var text: String
var body: some View {
Text(text)
}
init(_ text: String) {
print("Creating a new CustomText")
self.text = text
}
}
//----------------------
struct ContentView: View {
var body: some View {
ScrollView(.vertical) {
VStack(spacing: 10) {
ForEach(0..<100) {
CustomText("Item \($0)")
.font(.title)
}
}
.frame(maxWidth: .infinity)
}
// List {
// ForEach(0..<100) {
// CustomText("Item \($0)")
// .font(.title)
// }
// }
}
}
NavigationLinkを使用して新しいビューをスタックにプッシュする
Pushing new views onto the stack using NavigationLink
NavigationView
ビュースタックシステム
NavigationLink
SwiftUIで私が気に入っている点の1つは、NavigationLinkあらゆる宛先ビューで使用できることです。はい、カスタムビューを設計してプッシュできますが、テキストに直接プッシュすることもできます。
NavigationView {
VStack {
NavigationLink(destination: Text("Detail View")) {
Text("Hello World")
}
}
.navigationBarTitle("SwiftUI")
}
戻るボタンになり、それをタップするか、左端からスワイプして戻ることができます。
NavigationLink トピックをより深く掘り下げているように、ユーザーの選択に関する詳細を表示するためのものです。
sheet() 設定や作成ウィンドウなど、無関係なコンテンツを表示するためのものです。
struct ContentView: View {
var body: some View {
NavigationView {
List(0..<100) { row in
//Text("Row \(row)")
NavigationLink(destination: Text("Detail \(row)")) {
Text("Row \(row)")
}
}
.navigationBarTitle("SwiftUI")
}
}
}
NavigationLinkとその閉じ中かっこをコメントアウトした場合)は、インジケーターが消えているのがわかります。
階層的なCodableデータの操作
Working with hierarchical Codable data
import SwiftUI
struct User: Codable {
var name: String
var address: Address
}
struct Address: Codable {
var street: String
var city: String
}
struct ContentView: View {
var body: some View {
Button("Decode JSON") {
let input = """
{
"name": "Taylor Swift",
"address": {
"street": "555, Taylor Swift Avenue",
"city": "Nashville"
}
}
"""
// more code to come
let data = Data(input.utf8)
let decoder = JSONDecoder()
if let user = try? decoder.decode(User.self, from: data) {
print(user.address.street)
}
}
}
}