[英]How can I stop position modifier from changing size of View after modification in SwiftUI?
我正在將我的View/Content導入到CustomView進行一些修改和處理,如果我在我的輸入View/Content上使用 position 修飾符,並且在導入之前,在導入View/Content之后,它會自行占用屏幕大小,無論是否原始大小太大或太小,換句話說,position 修飾符,無論如何都會返回所有屏幕。 所以這給我帶來了問題和問題,因為我需要讀取導入的View/Content的真實和真實大小,我如何在我的 CustomView 中讀取我導入的View/Content的真實和真實大小? 考慮到這一點,我需要在導入之前在我的視圖/內容上使用 position。 並且將 Size 和 View 一起導入不是很酷,也不是很方便。 謝謝
import SwiftUI
struct ContentView: View {
var body: some View {
CustomView {
// Rectangle()
// .fill(Color.blue)
// .frame(width: 200, height: 1000, alignment: .center)
// //.position(x: 200, y: 100) // <<: this part make our View lose its original size!
Text("Hello, world!")
.padding()
.background(Color.yellow)
//.position(x: 200, y: 100) // <<: this part make our View lose its original size!
}
}
}
struct CustomView<Content: View>: View {
var content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) { self.content = content }
var body: some View {
return content()
.background( GeometryReader { geometry in Color.clear.onAppear() { print(geometry.size) } } )
}
}
使用offset()
而不是position()
因為它不會改變CustomView的原始尺寸,盡管它改變了Text("Hello, world!")的位置。
Text("Hello, world!")
.padding()
.background(Color.yellow)
.offset(x: 0, y: -350)
本文深入解釋了它們的區別。
https://www.hackingwithswift.com/books/ios-swiftui/absolute-positioning-for-swiftui-views
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.