今日は、ビューレイアウトに関するテクニックプロジェクトを続行し、使用可能な最も強力なレイアウトビューの1つを探索しますGeometryReader。これにより、実行時にビューのサイズと位置を読み取り、時間とともに変化するこれらの値を読み取り続けることができます。
おそらくそれほど特別に聞こえないかもしれませんが、見栄えがよく、作成するのに1行または2行のコードしか必要としない多くの魅力的な効果への扉が開かれます。はい、1つまたは2つGeometryReaderです。動作を理解したら、少し時間をかけて実験できることを願っています。
イギリスの詩人ウィリアムブレイクがかつて言ったように、「本当の知識の方法は実験である」ので、もしあなたが本当にこれを頭にくっつけたいなら、それで遊んでみるべきです!
SwiftUIビューの絶対配置
Absolute positioning for SwiftUI views
GeometryReader内のフレームと座標を理解する
Understanding frames and coordinates inside GeometryReader
GeometryReader
GeometryReaderを使用したScrollView効果
ScrollView effects using GeometryReader
//
// ContentView.swift
// LayoutAndGeometry
import SwiftUI
struct OuterView: View {
var body: some View {
VStack {
Text("Top")
InnerView()
.background(Color.green)
Text("Bottom")
}
}
}
struct InnerView: View {
var body: some View {
HStack {
Text("Left")
GeometryReader { geo in
Text("Center")
.background(Color.blue)
// On Tap!!
.onTapGesture {
print("Global center: \(geo.frame(in: .global).midX) x \(geo.frame(in: .global).midY)")
print("Custom center: \(geo.frame(in: .named("Custom")).midX) x \(geo.frame(in: .named("Custom")).midY)")
print("Local center: \(geo.frame(in: .local).midX) x \(geo.frame(in: .local).midY)")
}
}
.background(Color.orange)
Text("Right")
}
}
}
/*
struct ContentView: View {
let colors: [Color] = [.red, .green, .blue, .orange, .pink, .purple, .yellow]
var body: some View {
GeometryReader { fullView in
ScrollView(.vertical) {
ForEach(0..<50) { index in
GeometryReader { geo in
Text("Row #\(index)")
.font(.title)
.frame(width: fullView.size.width)
.background(self.colors[index % 7])
//.rotation3DEffect(.degrees(Double(geo.frame(in: .global).minY) / 5), axis: (x: 0, y: 1, z: 0))
.rotation3DEffect(.degrees(Double(geo.frame(in: .global).minY - fullView.size.height / 2) / 5), axis: (x: 0, y: 1, z: 0))
}
.frame(height: 40)
}
}
}
}
}
*/
/*
struct ContentView: View {
let colors: [Color] = [.red, .green, .blue, .orange, .pink, .purple, .yellow]
var body: some View {
GeometryReader { fullView in
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(0..<50) { index in
GeometryReader { geo in
Rectangle()
.fill(self.colors[index % 7])
.frame(height: 150)
.rotation3DEffect(.degrees(-Double(geo.frame(in: .global).midX - fullView.size.width / 2) / 10), axis: (x: 0, y: 1, z: 0))
}
.frame(width: 150)
}
}
.padding(.horizontal, (fullView.size.width - 150) / 2)
}
}
.edgesIgnoringSafeArea(.all)
}
}
*/
struct ContentView: View {
var body: some View {
OuterView()
.background(Color.red)
.coordinateSpace(name: "Custom")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}


