[英]Horizontal Paging Scrollview with TabView, SwiftUI
I'm trying to make a 3 paged tabview with 3 images for each page.我正在尝试制作一个 3 页的 tabview,每页有 3 个图像。 Paging is OK but tabview creates a vertical scroll for my images and pushes them to the bottom.分页没问题,但 tabview 为我的图像创建了一个垂直滚动并将它们推到底部。
VStack{
TabView(selection: $currentIndex.animation()) {
ForEach(0 ..< 3, id: \.self) {i in
VStack{
Image("wp\(i + 1)")
}.background(Color.blue)
}
}.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never)).background(Color.yellow)
}
Any idea why that happens?知道为什么会这样吗?
To make sure the view doesn't scroll you can limit the image sizes and let them resize to a certain height.为了确保视图不会滚动,您可以限制图像大小并让它们调整到某个高度。
In the code below I use GeometryReader and Image modifiers to put as many images as you want per tab with no vertical scrollbar:在下面的代码中,我使用 GeometryReader 和 Image 修饰符在每个选项卡上放置任意数量的图像,没有垂直滚动条:
struct ContentView : View {
@State var currentIndex:Int = 0
@State var imagesPerTab:Int = 1
var body: some View {
GeometryReader { geo in
// limit image height within 90% of tab height
// this guarantees the images will not cause a vertical scroll
let heightPerImage = (geo.size.height * 0.9) / CGFloat(imagesPerTab)
VStack {
// added a button to see effect of adding as many images as wanted
Button(action:{imagesPerTab += 1}) {
Image(systemName:"plus.app")
.resizable()
.aspectRatio(contentMode:.fit)
.frame(height:geo.size.height * 0.05) // button can only be 5% of height
}
TabView(selection: $currentIndex.animation()) {
ForEach(0 ..< 3, id: \.self) {i in
// tab
VStack(spacing:0) { // remove vertical spacing between images
ForEach(0 ..< imagesPerTab, id: \.self) {_ in
Image(systemName:"flame")
.resizable() // image resize freely
.aspectRatio(contentMode:.fit) // image doesn't skew
.frame(height:heightPerImage) // limit image to this height
}
}
.background(Color.blue)
}
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
.background(Color.yellow)
}
}
}
}
resizable()
before adding a frame()
.要调整它的大小,我们必须在添加frame()
resizable()
) 。GeometryReader
is used.为了获得视图本身可以获得的尺寸,使用了GeometryReader
。tag
is used to do the selection, so that the type of the selection variable and the type of tag parameter should be the same. tag
是用来做选择的,所以选择变量的类型和标签参数的类型应该是一样的。
struct ContentView: View {
@State var selection = 0
var body: some View {
VStack{
TabView (selection: $selection){
ForEach(0 ..< 3, id: \.self) {i in
VStack{
GeometryReader { proxy in //<- here
Image(systemName: "pencil")
.resizable()
.aspectRatio(contentMode: .fit) //<- here
.frame(width: proxy.size.width, height: proxy.size.height, alignment: .center) //<- here
.tag(i) //to get selection
}
}.background(Color.blue)
}
}.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never)).background(Color.yellow)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.