How do I change background color of UITabItem when item is selected

前端 未结 11 1071
暖寄归人
暖寄归人 2021-02-01 19:15

I would like a different background color when the user selects a tab bar item than when it is unselected.

11条回答
  •  梦如初夏
    2021-02-01 19:29

    UPDATE: As of iOS 7.1 this technique no longer works (if the user taps the same tab twice in succession, the background colour is cleared).


    UITabBarItem is a subclass of UIBarItem, everything is more painful because UIBarItem doesn't subclass UIView; however, UITabBarItem contains one. What follows manipulates that view, and therefore might be rejected if submitted to the AppStore.

    1) Subclass UITabBarItem

    Create a subclass of UITabBarItem and add a new selected property to its header, like so:

    @interface ALDTabBarItem : UITabBarItem
    @property (nonatomic, assign, getter = isSelected) BOOL selected;
    @end
    

    UITabBarItems have a view property, but it isn't exposed. We can extend the class to access it, and then create a custom setter on the selected property to change the background colour, like so:

    #import "ALDTabBarItem.h"
    
    @interface ALDTabBarItem (ALD)
    @property (nonatomic, strong) UIView *view;
    @end
    
    @implementation ALDTabBarItem
    
    - (void)setSelected:(BOOL)selected
    {
        if(selected)
            self.view.backgroundColor = [UIColor redColor];
        else
            self.view.backgroundColor = [UIColor clearColor];
    } 
    
    @end
    

    2) Update your UITabBarController delegate

    Add the following code to the delegate of your UITabBarController, which sets the selected states of the UITabBar:

    - (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
    {
        for(ALDTabBarItem *myItem in tabBar.items)
            myItem.selected = (myItem == item);
    }
    

提交回复
热议问题