iOS14下如何调整TabView图标尺寸?
解决iOS14+ TabView图标尺寸无法缩小的问题
我完全懂你这种困扰——升级iOS14后,TabView的tabItem图标突然变了尺寸,而且直接给Image加.font(.system(size:15))根本没效果,这是因为iOS14之后苹果给TabView的tabItem加了更强的默认样式约束,直接修改字体大小的方式不再生效了。
下面给你两个实用的解决方案:
方案一:用resizable() + frame()强制控制图标尺寸
系统SF Symbols图标是矢量的,我们可以通过让图片可缩放,再设置固定宽高来强制修改尺寸,这是最直接有效的方法。修改你的代码如下:
TabView(selection: self.$authVM.selectedTab) { HomeTab() .tabItem { Image(systemName: "house.fill") .renderingMode(.template) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 15, height: 15) Text("Home") }.tag(SelectedTab.home) SwapsTab() .tabItem { Image(systemName: "hand.draw.fill") .renderingMode(.template) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 15, height: 15) Text("Swaps") }.tag(SelectedTab.swaps) DiscoverTab() .tabItem { Image(systemName: "gamecontroller.fill") .renderingMode(.template) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 15, height: 15) Text("Discover") }.tag(SelectedTab.discover) NotificationsTab() .tabItem { Image(systemName: "bell.fill") .renderingMode(.template) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 15, height: 15) Text("Notifications") }.tag(SelectedTab.notifications) MessagesTab() .tabItem { Image(systemName: "envelope.fill") .renderingMode(.template) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 15, height: 15) Text("Messages") }.tag(SelectedTab.messages) }
这里的关键点是:
.resizable()让图片可以被缩放.aspectRatio(contentMode: .fit)保证图标不会变形.frame(width: 15, height: 15)直接指定你想要的尺寸
方案二:自定义tabItem视图(进阶)
如果需要更灵活的布局(比如调整图标和文字的间距、自定义对齐方式),可以把图标和文字包裹在一个自定义的VStack里,再传给tabItem:
// 先定义一个自定义的TabItem视图 struct CustomTabItem: View { let systemImage: String let title: String let iconSize: CGFloat var body: some View { VStack(spacing: 4) { // 自定义图标和文字的间距 Image(systemName: systemImage) .renderingMode(.template) .resizable() .aspectRatio(contentMode: .fit) .frame(width: iconSize, height: iconSize) Text(title) .font(.caption) // 也可以顺便调整文字大小 } } } // 然后在TabView里使用 TabView(selection: self.$authVM.selectedTab) { HomeTab() .tabItem { CustomTabItem(systemImage: "house.fill", title: "Home", iconSize: 15) }.tag(SelectedTab.home) // 其他tabItem同理替换 }
这种方式适合需要统一管理所有tabItem样式的场景,后续修改尺寸或样式只需要改自定义视图即可。
内容的提问来源于stack exchange,提问作者Halil İbrahim YÜCE




