![](/img/trans.png)
[英]SwiftUI LazyHStack TabView inside ScrollView is hidden
[英]Horizontal Paging Scrollview with TabView, SwiftUI
我正在尝试制作一个 3 页的 tabview,每页有 3 个图像。 分页没问题,但 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)
}
知道为什么会这样吗?
为了确保视图不会滚动,您可以限制图像大小并让它们调整到某个高度。
在下面的代码中,我使用 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)
}
}
}
}
frame()
resizable()
) 。GeometryReader
。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.