Remove UITabBarItem

风流意气都作罢 提交于 2019-12-09 12:53:52

问题


How can I remove a UITabBarItem from a UITabBar?

I haven't tried anything, because I haven't found anything from Google searches or the documentation for UITabBar, UITabBarController, or UITabBarItem.

Thanks in advance! :)


回答1:


UITabBar has an NSArray collection of items. Since the items property is an NSArray and not an NSMutableArray, you'd have to construct a new NSArray from the existing one devoid of the object you want to remove, then set the items property to the new array.

/* suppose we have a UITabBar *myBar, and an int index idx */
NSMutableArray *modifyMe = [[myBar items] mutableCopy];
[modifyMe removeObjectAtIndex:idx];
NSArray *newItems = [[NSArray alloc] initWithArray:modifyMe];
[myBar setItems:newItems animated:true];



回答2:


Mike Caron's advice will throw an exception if you intend to modify a tabBar that belongs to a controller.

In iOS 3.0 and later, you should not attempt to use the methods and properties of this class to modify the tab bar when it is associated with a tab bar controller object. Modifying the tab bar in this way results in the throwing of an exception. Instead, any modifications to the tab bar or its items should occur through the tab bar controller interface. You may still directly modify a tab bar object that is not associated with a tab bar controller.

In this case self.tabBarItem=nil will remove it.




回答3:


NOTE: this appears to not work in iOS 11. It was still good in iOS 10.

This is a moderately horrible answer, in my opinion, in part because it's subverting the human interface guidelines, but all the same it seems to work cleanly:

UITabBar *oldbar = self.tabBarController.tabBar;
UITabBar *newbar = [[UITabBar alloc] initWithFrame:CGRectMake(0,0,oldbar.frame.size.width,oldbar.frame.size.height)];
NSMutableArray *olditems = [[oldbar items] mutableCopy];
[olditems removeObjectAtIndex:0];
NSArray *newitems = [[NSArray alloc] initWithArray:olditems];
[newbar setItems:newitems animated:false];
[oldbar addSubview:newbar];

That layers it cleanly on top of the old tabbar, and it maintains its functionality.



来源:https://stackoverflow.com/questions/4037160/remove-uitabbaritem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!