首页 > 解决方案 > SwiftUI:在 TabView 中调整图像的位置

问题描述

我使用以下代码创建一个TabViewwith SwiftUI

struct TabbedView: View {
    @State private var selected = 0

    var body: some View {
        TabView(selection: $selected) {
            View1().tabItem {
                Image("Tab1")
            }.tag(1)

            View2().tabItem {
                Image("Tab2")
                .offset(y: 20) //<--- has no effect
                }.tag(2)

            View3().tabItem {
                Image("Tab3")
            }.tag(3)
        }
    }
}

我只Image对没有文本的选项卡项使用视图,结果如下:

在此处输入图像描述

我需要将Image视图定位(或垂直对齐)到中心,TabView但找不到直接的方法。

标签: iosswiftswiftuitabview

解决方案


标准TabView现在不允许更改tabItem内容的对齐方式......但可以根据以下内容创建自定义浮动选项卡状项目Button,这将允许对齐和/或自定义外观并仍然以编程方式激活 TabView 项目。

struct TabbedView: View {
    @State private var selected = 0

    var body: some View {
        ZStack(alignment: Alignment.bottom) {
            TabView(selection: $selected) {
                View1().tabItem {
                    Text("") // < invisible tab item
                }.tag(1)

                View2().tabItem {
                    Text("")
                    }.tag(2)

                View3().tabItem {
                    Text("")
                }.tag(3)
            }
            // tab-items cover - do anything needed, height, position, alignment, etc.
            HStack { 
                Button(action: { self.selected = 1 } ) {
                    Image("Tab1") // << align & highlight as needed
                }
                Button(action: { self.selected = 2 } ) {
                    Image("Tab2") // << align & highlight as needed
                }
                Button(action: { self.selected = 3 } ) {
                    Image("Tab3") // << align & highlight as needed
                }
            }
        }
    }
}

注意:它甚至可以是没有按钮的,只是带有点击手势的图像等。


推荐阅读