![](/img/trans.png)
[英]SwiftUI: How to center a view vertically and horizontally inside of a container view and put something under it
[英]How to horizontally and vertically center an image inside a scrollview in SwiftUI
想象一個簡單的滾動視圖,其中包含一個帶有圖像的內容視圖,如果高度小於滾動視圖的高度,則該圖像應該垂直居中。
如果圖像超過滾動視圖的高度,則滾動視圖應允許滾動以顯示完整的圖像。
此外,如果圖像比它的容器窄,它應該水平居中。
縮小圖像時,應始終保持其固有 aspectRatio 。
這些是要求
你會如何在 SwiftUI 中做到這一點?
Stackoverflow 上的類似問題(沒有真正解決問題):
一種建議的解決方案如下:
struct TestView: View {
let image: UIImage
var body: some View {
GeometryReader { geo in
ScrollView {
SwiftUI.Group {
Image(uiImage: self.image)
// make image resizable to expand to frame's bounds
.resizable()
// make sure the aspect ratio when scaling is
// like the original image ratio
.aspectRatio(contentMode: .fit)
// limit the image's width to its intrinsic width
// this gets rid of **upscaling**
.frame(maxWidth: image.size.width)
}
// makes sure the container is always at least as tall as the scrollview
// so that the **vertical alignment** works properly
// additionally we let the frame expand horizontally to the edges of
// the scrollview for horizontal centering to work
.frame(maxWidth: geo.size.width, minHeight: geo.size.height)
}
}
}
}
添加了注釋來解釋每個命令的用途。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.