iOS 设置tabBar点击后Item的背景颜色.
时间: 2023-05-11 17:05:25 浏览: 84
你可以通过设置 UITabBarItem 的 selectedImage 属性来实现这个功能。具体来说,你可以创建一个带有背景颜色的 UIImage,然后将其设置为 selectedImage。例如:
```
UIImage *selectedImage = [UIImage imageNamed:@"tabbar_selected_background"];
selectedImage = [selectedImage resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
[[UITabBarItem appearance] setSelectedImage:selectedImage];
```
这将会将所有的 tabBar item 的选中状态下的背景颜色设置为 tabbar_selected_background 这张图片的背景颜色。你可以根据自己的需要修改这个图片的颜色和大小。
注意:这个方法只适用于 iOS 5 及以上版本。如果你需要支持 iOS 4,你需要使用自定义的 tabBar 来实现这个功能。
相关问题
ios 设置tabbar背景颜色
您可以通过设置 UITabBar 的背景颜色来更改 TabBar 的颜色。以下是一个简单的示例代码:
```
// Swift 5
let tabBar = self.tabBarController?.tabBar
tabBar?.barTintColor = UIColor.red
// Objective-C
UITabBar *tabBar = self.tabBarController.tabBar;
[tabBar setBarTintColor:[UIColor redColor]];
```
请注意,这将更改整个 TabBar 的背景颜色。如果要更改选中和未选中项目的颜色,则需要使用其他属性和方法。
ios设置tabbar背景颜色_iOS 13 TabBar的字体颜色及背景颜色的设置
iOS 13中设置TabBar的背景颜色和字体颜色需要使用新的API。以下是设置TabBar背景颜色和字体颜色的示例代码:
```
// 设置TabBar的背景颜色
if #available(iOS 13.0, *) {
let appearance = UITabBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = .red // 设置背景颜色
tabBar.standardAppearance = appearance
} else {
tabBar.barTintColor = .red
}
// 设置TabBar的字体颜色
if #available(iOS 13.0, *) {
let appearance = UITabBarAppearance()
appearance.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.green] // 设置正常状态下的字体颜色
appearance.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor.blue] // 设置选中状态下的字体颜色
tabBar.standardAppearance = appearance
} else {
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.green], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.blue], for: .selected)
}
```
需要注意的是,iOS 13中可以使用`UITabBarAppearance`来设置TabBar的样式,但在iOS 12及以下系统中需要使用`UITabBarItem.appearance()`来设置。