我正在开发一个应用程序,想要自定义UITabBar图标图像。
我有一张名为about.png的图片,我想将其设置为我的应用程序UITabBar的左侧图标图像。我该怎么做?
我正在开发一个应用程序,想要自定义UITabBar图标图像。
我有一张名为about.png的图片,我想将其设置为我的应用程序UITabBar的左侧图标图像。我该怎么做?
如果您使用此代码并使用自己的图片而不是内置的图片,请进行以下操作:
- (id)init {
UIImage* anImage = [UIImage imageNamed:@"newspaper.png"];
UITabBarItem* theItem = [[UITabBarItem alloc] initWithTitle:@"News" image:anImage tag:0];
self.tabBarItem = theItem;
[theItem release];
return self; }
newspaper.png 是我在选项卡栏中自己的图像...
好的,现在这样已经足以解决你的问题了...
如果你想要更改 UITabbarItem 的图片,你可以利用它的实例方法。
- (id)initWithTitle:(NSString *)title image:(UIImage *)image tag:(NSInteger)tag
- (id)init {
if (self = [super initWithNibName:@"Search" bundle:nil]) {
UIImage* tabImage = [UIImage imageNamed:@"search.png"];
UITabBarItem* theItem = [[UITabBarItem alloc] initWithTitle:@"Search" image:tabImage tag:0];
self.tabBarItem = theItem;
[theItem release];
}
return self;
}
这个可以通过编程或者使用可视化界面(IB)两种方式来实现。
编程实现:
UITabBarItem* theItem = [[UITabBarItem alloc] initWithTitle:@"News" image:anImage tag:0];
如果你正在进行可视化操作,可以使用以下方法:
在 IB 中单击特定的选项卡图标,选择自定义图标并命名特定的图标文件。
希望这能解决你的问题...
首先,您需要编写以下代码来创建一个类:
extension UITabBarController {
func addIcon(icon : UIImage, deselectIcon : UIImage, buttonIndex : Int, currentPage : Int){
var index = 0
for view in view.subviews {
if view.subviews.count > 3 {
for _view in view.subviews {
if index == buttonIndex {
for v in _view.subviews {
if v is UIImageView {
v.removeFromSuperview()
}
}
let img = UIImageView(frame: CGRect(x: _view.frame.width / 2 - 15, y: 4, width: 30, height: 30))
if buttonIndex == currentPage {
img.image = icon
}else{
img.image = deselectIcon
}
img.contentMode = .scaleAspectFit
_view.addSubview(img)
}
index += 1
}
}
}
}
}
didload
中你调用函数:override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1 ) {
self.tabBarController?.addIcon(icon: #imageLiteral(resourceName: "Shop"), deselectIcon: #imageLiteral(resourceName: "Shop"), buttonIndex: 1, currentPage: 1)
}
}
override func viewWillAppear(_ animated: Bool) {
tabBarController?.addIcon(icon: #imageLiteral(resourceName: "Shop"), deselectIcon: #imageLiteral(resourceName: "Shop"), buttonIndex: 1, currentPage: 1)
}
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
if([tabBarController selectedIndex] == 0)
{
[viewController.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"selected.png"]withFinishedUnselectedImage:[UIImage imageNamed:@"unselect.png"]];
}
}
通过这个方法,你可以更改你的选项卡图标。
或者你可以直接在你的视图控制器的init(或ViewWillAppear)方法中使用,例如:
[viewController.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"selected.png"]withFinishedUnselectedImage:[UIImage imageNamed:@"unselect.png"]];