UITabBarController – TAB bar controller

A container view controller used to manage a radio-style selection interface that determines which child view controllers to display based on the selection.

The UITabBarController object displays a TAB bar interface with tabs at the bottom of the window for selecting between modes and displaying a view of that mode. This class is usually used as-is, but can also be subclassed.

Each TAB in the TAB bar controller interface is associated with a custom view controller. When the user selects a particular TAB, the TAB bar controller displays the root view of the corresponding view controller, replacing any previous view (the user clicks on the root view that always shows the TAB, regardless of which TAB was previously selected. This is true even if the tag is already selected). Because selecting a tag replaces the contents of the interface, the interface types managed in each tag need not be similar in any way. In fact, tabbed interfaces are often used to represent different types of information, or to represent the same information with completely different interface styles.

Never directly access the TAB bar view of the TAB bar controller. To configure the labels for the TAB bar controller, assign the View controller that provides the root view for each label to the viewControllers property. The order in which you specify view controllers determines the order in which they appear in the TAB bar. When setting this property, you should also assign a value to the selectedViewController property to indicate which view controller was originally selected. (You can also use the selectedIndex property to select view controllers by array index.) When a TAB bar controller’s view is embedded in an application window (obtained using inherited view properties), the TAB bar controller automatically selects the view controller and displays its content, resizing it to fit the TAB bar interface as needed.

Each TAB bar item is configured through their corresponding view controller. To associate a tabBarItem with a view controller, create a new instance of the UITabBarItem class, configure it appropriately for the view controller, and assign it to the view controller’s tabBarItem property. If a custom TAB bar item is not provided to the view controller, the view controller creates a default item that does not contain images and text from the view controller’s title property.

When the user interacts with the TAB bar interface, the TAB bar controller object sends notifications to its agent about the interaction. The agent can be any object you specify, but must abide by the UITabBarControllerDelegate agreement. You can use proxies to prevent specific TAB bar items from being selected and to perform other tasks when the TAB is selected. You can also use delegates to monitor changes made to the TAB bar by the More navigation controller.

Commonly used attributes

@property(nullable, nonatomic,copy) NSArray<__kindof UIViewController *> *viewControllers;

Property description: Array of root view controllers displayed on the TAB bar interface. The default value for this property is nil. When configuring a label bar controller, you can use this property to specify the content for each label on the TAB bar interface. The order of view controllers in the array corresponds to the order in which they are displayed in the TAB bar. Therefore, the controller with index 0 corresponds to the leftmost label, the controller with index 1 to the next label on the right, and so on. If there are more view controllers than tabs, the view controller at the end of the array is managed by the MORE navigation controller, but the MORE navigation controller itself is not included in the array.

@property(nullable, nonatomic,copy) NSArray<__kindof UIViewController *> *viewControllers;
Copy the code

@property(nullable, nonatomic, assign) __kindof UIViewController *selectedViewController;

Property Description: View controller associated with the currently selected TAB item. The custom view of this view controller is currently displayed by the TAB bar interface. The specified view controller must be in the viewControllers array. Specifying a new view controller to this property changes the view currently displayed and selects the appropriate label in the TAB bar. Changing the view controller updates the selectedIndex property accordingly. The default value for this property is nil. In iOS 3.0 and later, you can use this property to select any view controller in the viewControllers property. This includes view controllers that are managed by the MORE controller and whose TAB bar items are not visible in the TAB bar. You can also use it to select the More NavigationController itself, which is available from the moreNavigationController property.

@property(nullable, nonatomic, assign) __kindof UIViewController *selectedViewController;
Copy the code

@property(nonatomic) NSUInteger selectedIndex;

Property Description: Index of the view controller associated with the currently selected TAB item. This property nominally represents the index of the viewControllers property array. However, if the selected view controller is currently a MORE (more) navigation controller, this property contains the value NSNotFound. Setting this property changes the selected view controller to the view controller at the specified index in the viewControllers array. To select more navigation controllers themselves, you must change the value of the selectedViewController property.

@property(nonatomic) NSUInteger selectedIndex;
Copy the code

@property(nonatomic, readonly) UINavigationController *moreNavigationController API_UNAVAILABLE(tvOS);

Property Description: View controllers that manage more navigation interfaces. This property always contains a valid More navigation controller, even if the More button is not displayed on the screen. You can use the value of this property to select more navigation controllers in the TAB bar interface, or compare it to the currently selected view controller.

Do not manually add objects stored in this property to the TAB bar interface. The More controller is automatically displayed on the TAB bar controller as needed. You also cannot look for More navigation controllers in the array of viewControllers stored in the viewControllers property. The TAB bar controller does not include the More navigation controller in the object array.

@property(nonatomic, readonly) UINavigationController *moreNavigationController API_UNAVAILABLE(tvOS);
Copy the code

@property(nullable, nonatomic, copy) NSArray<__kindof UIViewController *> *customizableViewControllers API_UNAVAILABLE(tvOS);

Property Description: A subset of customizable view controllers managed by this TAB bar controller. This property controls which items in the TAB bar the user can rearrange. When the user clicks “More” on the TAB bar view, a custom interface appears that displays any items that do not fit into the main TAB bar. The interface also contains an edit button that allows the user to rearrange items. You can only rearrange items of its associated view controller in this array from this interface. If the array is empty or the value of this property is nil, the TAB bar does not allow any items to be rearranged. ViewControllers change the value of the attribute (directly or use setViewControllers: animated: method) will change the value of this attribute. When first specified to a TAB bar controller, all view controllers are customizable by default.

@property(nullable, nonatomic, copy) NSArray<__kindof UIViewController *> *customizableViewControllers API_UNAVAILABLE(tvOS);
Copy the code

@ property (nonatomic, readonly) UITabBar * tabBar API_AVAILABLE (ios (3.0));

Property Description: TAB bar view associated with this controller. You should not attempt to manipulate the UITabBar object itself stored in this property. If you try to do so, the TAB bar view throws an exception. To configure items for the TAB bar interface, specify one or more custom viewControllers to the viewControllers property instead. The TAB bar collects the required TAB bar items from the specified view controller.

@ property (nonatomic, readonly) UITabBar * tabBar API_AVAILABLE (ios (3.0));Copy the code

@property(nullable, nonatomic,weak) id delegate;

Property description: Proxy object for the TAB bar controller. You can use proxy objects to track changes to items in the TAB bar and monitor the selection of TAB items. Provide the proxy objects should conform to UITabBarControllerDelegate agreement. The default value for this property is nil.

@property(nullable, nonatomic,weak) id<UITabBarControllerDelegate> delegate;
Copy the code
Common proxy functions provided by UITabBarController

– (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *) viewController API_AVAILABLE (ios (3.0));

Function description: Asks the agent whether the specified view controller should be set to active. The TAB bar controller calls this method in response to a user clicking on an item in the TAB bar. You can use this method to dynamically decide whether to set a given label as an active label.

Parameters:

TabBarController: the tabBarController that contains the viewController.

ViewController: the viewController that belongs to the TAB that the user clicks.

Return value: Returns YES if the view controller’s label should be selected, or NO if the currently selected label should remain active (and the selected label remains selected).

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *) viewController API_AVAILABLE (ios (3.0));Copy the code

– (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;

Function description: Tells the delegate user to select a TAB item in the TAB bar. In iOS V3.0 and later, the TAB bar controller calls this method regardless of whether the selected view controller changes. In addition, it is only called when the user clicks on the TAB bar and is not called when code is used to programmatically change the contents of the TAB bar.

Parameters:

TabBarController: the tabBarController that contains the viewController.

ViewController: the viewController selected by the user. In iOS V3.0 and later, this might be the same view controller that was selected.

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;
Copy the code

UITabBar – TAB bar

UITabBar TAB bar, a control in which you can display one or more buttons to choose between different subtasks, views, or modes in your application. In general, TAB bars can be used in conjunction with UITabBarController objects, but they can also be used as stand-alone controls in an application. The TAB bar is always displayed at the bottom edge of the screen and displays the contents of one or more UITabBarItem objects. The appearance of the TAB bar can be customized using a background image or a light color to meet the needs of the interface. Click on an item selection and highlight the item, then use the item selection to enable the appropriate pattern for the application.

The TAB bar can be configured programmatically or in Interface Builder. The UITabBarController object provides its own TAB bar object. To use UITabBarController, you must configure to provide the UITabBar object. When creating a TAB bar programmatically, use the initWithFrame: method or another view initializer method to set its initial configuration. Use this method to configure the appearance of the TAB bar. You can also use this method to specify the items displayed in the TAB bar you created.

The UITabBar class and the UIToolbar class have a similar look but different purposes. Use the TAB bar (UITabBar) to communicate and change the mode of your application. Use the UIToolbar to present the user with a set of actions related to what is currently displayed.

Commonly used attributes

@property(nullable, nonatomic, weak) id delegate;

Property description: Proxy object for the TAB bar. Use proxies to track the selection of TAB bar items and respond to user customization of TAB bars. The default value of this property is nil.

@property(nullable, nonatomic, weak) id<UITabBarDelegate> delegate;
Copy the code

@property(nullable, nonatomic, copy) NSArray<UITabBarItem *> *items;

Attribute Description: Items displayed in the TAB bar. This property contains an array of UITabBarItem objects, each corresponding to a label displayed by the label bar. The order of items in this property corresponds to the order of items on the screen. You can use this property to access these items as needed.

For the TAB bar you create, you can assign a new set of items to this property to change the items displayed. Changing items replaces them immediately, without animation. If the TAB bar is managed by the UITabBarController object, this property cannot be modified; doing so will throw an exception. When the label bar belongs to the label bar controller, use the label bar controller method to change the label bar. The default value of this property is nil.

@property(nullable, nonatomic, copy) NSArray<UITabBarItem *> *items;  
Copy the code

@property(nullable, nonatomic, weak) UITabBarItem *selectedItem;

Property Description: The currently selected item on the TAB bar. Use this property to get the currently selected item. If you change the value of this property, the TAB bar selects the corresponding item and updates the TAB bar appearance accordingly. Set the property to nil to clear the selection.

When an item is selected, the TAB bar displays the image in the selectedImage property of the TAB bar item. If the selectedImageTintColor property is set, the TAB bar will also apply the color from that property to the selected image. In order to prevent project system shading, use UIImageRenderingModeAlwaysOriginal renderer provide images. The default value of this property is nil.

@property(nullable, nonatomic, weak) UITabBarItem *selectedItem;
Copy the code

@property(nullable, nonatomic, strong) UIImage *backgroundImage API_AVAILABLE(ios(5.0)) UI_APPEARANCE_SELECTOR;

Property description: Tag bar custom background image. If a scalable background image is specified, the TAB bar stretches the image to fill the available space. If the image is not stretchable and not large enough to fill the available space, the TAB bar tiles the image. The UIImageResizingMode type in UIImage determines the stretching effect, and when there is a custom background image, the TAB bar does not draw any blur behind it, even if the translucency property is set to YES.

@property(nullable, nonatomic, strong) UIImage *backgroundImage API_AVAILABLE(ios(5.0)) UI_APPEARANCE_SELECTOR;
Copy the code

@property(nullable, nonatomic, strong) UIImage *shadowImage API_AVAILABLE(ios(6.0)) UI_APPEARANCE_SELECTOR;

Property description: Shadow image for the TAB bar. For a TAB bar with a custom background, you can use this property to specify a custom shadow image for the TAB bar. The shaded image lies outside the boundary of the TAB bar itself, usually above or below the frame rectangle of the TAB bar. The location depends on the current platform. For example, on the iPhone and iPad, the shaded image is placed above the TAB bar. This property must be used in conjunction with a custom background image. If the backgroundImage property is nil, the label bar ignores the value in this property and uses the default shadow.

@property(nullable, nonatomic, strong) UIImage *shadowImage API_AVAILABLE(ios(6.0)) UI_APPEARANCE_SELECTOR;
Copy the code

@ property (nonatomic, getter = isTranslucent) BOOL translucent API_AVAILABLE (ios (7.0));

Property description: A Boolean value indicating whether the TAB bar is translucent. When the TAB bar is translucent, need to configure the view controller edgesForExtendedLayout and extendedlayoutinclesopaquebars properties to display the TAB bar the following. The default value of this property is YES if the TAB bar does not have a custom background image, or if any pixel of the background image has an alpha value less than 1.0. If the background image is completely opaque, the default value of this property is NO. If you set this property to YES and the custom background image is completely opaque, UIKit applies a system-defined opacity of less than 1.0. If you set this property to NO and the background image is transparent, UIKit will add an opaque background.

@ property (nonatomic, getter = isTranslucent) BOOL translucent API_AVAILABLE (ios (7.0));Copy the code

@Property (nonatomic) UITabBarItemPositioning itemPositioning API_AVAILABLE(ios(7.0)) UI_APPEARANCE_SELECTOR API_UNAVAILABLE(tvOS);

Attribute Description: Indicates the location scheme of the label in the label bar. The default value of this attribute UITabBarItemPositioningAutomatic, according to the current environment leads to the default TAB bar positioning of the project:

  • In a horizontal, compact environment, the TAB bar distributes items throughout the space and adjusts the spacing as needed.
  • In a horizontal rule environment, the label bar uses the itemWidth and itemSpacing attributes to set the width and spacing between items, and positions those items in the center of the available space. This configuration may leave space on the left and right edges of the TAB bar. By changing the value of this property to a different value, you can enforce a specific positioning scheme.
@Property (nonatomic) UITabBarItemPositioning itemPositioning API_AVAILABLE(ios(7.0)) UI_APPEARANCE_SELECTOR API_UNAVAILABLE(tvOS);Copy the code

UITabBarItemPositioning Provides an enumeration value:

Typedef NS_ENUM(NSInteger, UITabBarItemPositioning) {// Specifies the automatic positioning of TAB entries based on user interface usage. The default value. UITabBarItemPositioningAutomatic, / / the project distribution in the entire width of the TAB bar. When UITabBarItemPositioningAutomatic option is selected, the TAB bar in the compact level environment using this kind of behavior. UITabBarItemPositioningFill, / / place project centered within the available space. When UITabBarItemPositioningAutomatic option is selected, the TAB bar in horizontal rules using this behavior in the environment. UITabBarItemPositioningCentered,} API_AVAILABLE (ios (7.0));Copy the code

For example, an opaque code snippet of the TAB bar with a red shadow

- (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (launchOptions NSDictionary *) {/ / create the window self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; UITabBarController *tabController = [[UITabBarController alloc]init]; Custom background image tabController / / tabs. The tabBar. BackgroundImage = [self imageWithColor: [UIColor clearColor] Size: CGSizeMake (CGRectGetWidth (tabController. The frame), 0.5)]; / / tabs custom shadow image tabController tabBar. ShadowImage = [self imageWithColor: [UIColor redColor] Size: CGSizeMake (CGRectGetWidth (tabController. The frame), 0.5)]; / / whether the TAB bar translucent tabController. TabBar. Translucent = NO; / / TAB bar item localization way tabController tabBar. ItemPositioning = UITabBarItemPositioningFill; self.window.rootViewController = tabController; // Display window [self.window makeKeyAndVisible]; return YES; } - (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {if (! color || size.width <= 0 || size.height <= 0) return nil; CGRect rect = CGRectMake(0, 0, size.width, size.height); UIGraphicsBeginImageContextWithOptions(rect.size,NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, color.CGColor); CGContextFillRect(context, rect); UIImage *image =UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }Copy the code

The style is shown as follows:

Common proxy functions provided by UITabBar

– (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;

Notifies the agent when the user selects an item in the TAB bar.

Parameters:

TabBar: indicates the tabBar

Item: indicates the selected label item

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;
Copy the code

UIBarItem — an item in the TAB bar

Derived from NSObject, an abstract superclass for items that can be added to the column displayed at the bottom of the screen. Each item behaves like a button (instance of UIButton). They have titles, images, actions, and targets. You can also enable and disable an item on the toolbar.

Commonly used attributes

@property(nonatomic,getter=isEnabled) BOOL enabled;

Property description: A Boolean value indicating whether the item is enabled. If it is “YES,” the item will be drawn in partial gray to indicate that it is disabled. The default value is YES.

@property(nonatomic,getter=isEnabled) BOOL         enabled; 
Copy the code

@property(nullable, nonatomic,copy) NSString *title;

Property Description: The title displayed on the project. This property should be set before adding items to the toolbar. The default is nil.

@property(nullable, nonatomic,copy)             NSString    *title; 
Copy the code

@property(nullable, nonatomic,strong) UIImage *image;

Property description: The image used to represent the item. This image can be used to create other images to represent the item on the column — for example, a selected and unselected image may be derived from that image. This property should be set before items are added to the toolbar. The default is nil.

@property(nullable, nonatomic,strong)           UIImage     *image;
Copy the code

@property(nonatomic) UIEdgeInsets imageInsets;

Property description: The position at which the image is inserted at the beginning of each edge. The default is UIEdgeInsetsZero.

@property(nonatomic)                  UIEdgeInsets imageInsets; 
Copy the code

For example, to set the spacing within a picture of an item:

UITabBarItem *tabBarItemCart = self.tabbar.items [0]; / / set the label of picture span tabBarItemCart. The imageInsets = UIEdgeInsetsMake (20, 0, 20, 0).Copy the code

UITabBarItem

Derived from UIBarItem, an item in the TAB bar. The TAB bar operates strictly in radio mode. Each time an item is selected, clicking on the TAB bar item will switch the view above the TAB bar. You can also specify a tag value on the TAB bar item to add additional visual information. For example, the Messages application uses a tag value on the project to display the number of new Messages. This class also provides a number of system defaults for creating items.

Using initWithTabBarSystemItem: tag: method to create a system. Use the initWithTitle: Image: Tag: method to create a custom project with the specified title and image that are used for both unselected and selected images. Using initWithTitle: image: selectedImage: with specified method to create a title, not selected image and selected custom project.

Commonly used attributes

@property(nullable, nonatomic,strong) UIImage *selectedImage API_AVAILABLE(ios(7.0));

Property description: The image displayed when a TAB bar item is selected. If nil, the value of the image property on the superclass UIBarItem will be used as both the unselected image and the selected image. By default, the actual selected image is automatically created based on the alpha value in the source image. To prevent the system from coloring, please provide UIImageRenderingModeAlwaysOriginal image.

@property(nullable, nonatomic,strong) UIImage *selectedImage API_AVAILABLE(ios(7.0));
Copy the code

@property(nullable, nonatomic, copy) NSString *badgeValue;

Property description: Text displayed in the upper right corner of the project with red ovals around it. The default is nil.

@property(nullable, nonatomic, copy) NSString *badgeValue;
Copy the code

@property (nonatomic, readwrite, copy, nullable) UIColor *badgeColor API_AVAILABLE(ios(10.0)) UI_APPEARANCE_SELECTOR;

Property description: The background color of the ellipse around the text displayed in the upper right corner of the project. If no value is specified for this property, the red background color is used by default.

@property (nonatomic, readwrite, copy, nullable) UIColor *badgeColor API_AVAILABLE(ios(10.0)) UI_APPEARANCE_SELECTOR;
Copy the code

Markup value text style:

Some attributes of UITabBarItem can also be accessed via KVC, such as adding a simple animation to the imageView property of UITabBarItem:

/ / find the shopping cart item labels UITabBarItem. * tabBarItemCart = rootController tabBar. Items [rootController. CartIndex]; UIImageView *cartView = [[tabBarItemCart valueForKey:@"_view"]valueForKey:@"_imageView"]; / / TAB bar view shopping cart zoom animation [cartView. Layer addAnimation: [self scaleAnimationFromValue: 1.0 toValue: duration 1.2:0.1 f fillMode:kCAFillModeRemoved] forKey:@"transform.scale"];Copy the code

UIViewController (UITabBarControllerItem) – Label bar controller item

Commonly used attributes

@property(null_resettable, nonatomic, strong) UITabBarItem *tabBarItem;

Property Description: When a view controller is added to a TAB bar controller, it represents the TAB bar items of the view controller. This is the only instance of UITabBarItem that is created to represent it when the view controller is a child of the TAB bar controller. The first time an attribute is accessed, a UITabBarItem is created. Therefore, if you do not use a label bar to display the controller, the label should not be displayed.

@property(null_resettable, nonatomic, strong) UITabBarItem *tabBarItem;
Copy the code

Example: A code snippet for setting the TAB items of a view controller in a TAB bar controller:

/ / set the title controller. TabBarItem. Title = @ "release"; / / set the graphics controller. TabBarItem. Image = [UIImage imageNamed: @ "tab_cart_normal"]. / / set the picture of the selected controller. TabBarItem. SelectedImage = [UIImage imageNamed: @ "tab_cart_selected"].Copy the code

@property(nullable, nonatomic, readonly, strong) UITabBarController *tabBarController;

Property description: The nearest TAB bar controller in the hierarchy as the parent of the view controller. If the view controller or one of its parents is a child of the TAB bar controller, this property contains the owning TAB bar controller.

@property(nullable, nonatomic, readonly, strong) UITabBarController *tabBarController;
Copy the code

Practice code

#import "AppDelegate.h"
#import "WGEssenceViewController.h"
#import "WGNewViewController.h"
#import "WGPublishViewController.h"
#import "WGFriendTrendViewController.h"
#import "WGMeViewController.h"

@interface AppDelegate ()<UITabBarControllerDelegate>

@property (nonatomic, strong) UIViewController *controller;//记录选中的新帖控制器

@end

@implementation AppDelegate

///程序启动时就会调用
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //创建窗口
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //设置根控制器
    UITabBarController *tabController = [[UITabBarController alloc]init];
    //设置代理
    tabController.delegate = self;
    //标签栏的自定义背景图像
    tabController.tabBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:CGSizeMake(CGRectGetWidth(tabController.view.frame), 0.5)];
    //标签栏的自定义阴影图像
    tabController.tabBar.shadowImage = [self imageWithColor:[UIColor redColor] size:CGSizeMake(CGRectGetWidth(tabController.view.frame), 0.5)];
    //标签栏是否半透明
    tabController.tabBar.translucent = NO;
    //标签栏项的定位方式
    tabController.tabBar.itemPositioning = UITabBarItemPositioningFill;
    self.window.rootViewController = tabController;
    //添加五个子控制器
    //精华
    WGEssenceViewController *essenceViewController = [[WGEssenceViewController alloc]init];
    [self tabBarControll:tabController addControllerToNavigationController:essenceViewController withWhetherNavigation:YES];
    //新帖
    WGNewViewController *newViewController = [[WGNewViewController alloc]init];
    [self tabBarControll:tabController addControllerToNavigationController:newViewController withWhetherNavigation:YES];
    //发布
    WGPublishViewController *publishViewController = [[WGPublishViewController alloc]init];
    [self tabBarControll:tabController addControllerToNavigationController:publishViewController withWhetherNavigation:NO];
    //关注
    WGFriendTrendViewController *friendTrendViewController = [[WGFriendTrendViewController alloc]init];
    [self tabBarControll:tabController addControllerToNavigationController:friendTrendViewController withWhetherNavigation:YES];
    //我
    WGMeViewController *meViewController = [[WGMeViewController alloc]init];
    [self tabBarControll:tabController addControllerToNavigationController:meViewController withWhetherNavigation:YES];
    //显示窗口
    [self.window makeKeyAndVisible];
    return YES;
}

///导航栏添加控制器
- (void)tabBarControll:(UITabBarController *)tabBarController addControllerToNavigationController:(UIViewController *)controller withWhetherNavigation:(BOOL)whetherNavigation{
    //判断是否是导航控制器
    if(whetherNavigation){
        //导航控制器
        UINavigationController *navigationController = [[UINavigationController alloc]initWithRootViewController:controller];
        [tabBarController addChildViewController:navigationController];
        //设置导航栏上的按钮 -> 由对应子控制器的tabBarItem属性
        if([controller isMemberOfClass:[WGEssenceViewController class]]){
            navigationController.tabBarItem.title = @"精华";
            navigationController.tabBarItem.image = [UIImage imageNamed:@"tab_home_normal"];
            navigationController.tabBarItem.selectedImage = [UIImage imageNamed:@"tab_home_index"];
            navigationController.tabBarItem.tag = 5000;
        }
        if([controller isMemberOfClass:[WGNewViewController class]]){
            navigationController.tabBarItem.title = @"新帖";
            navigationController.tabBarItem.image = [UIImage imageNamed:@"tab_category_normal"];
            navigationController.tabBarItem.selectedImage = [UIImage imageNamed:@"tab_category_selected"];
            navigationController.tabBarItem.badgeValue = @"5";
            navigationController.tabBarItem.badgeColor = [UIColor purpleColor];
            navigationController.tabBarItem.tag = 5001;
        }
        if([controller isMemberOfClass:[WGFriendTrendViewController class]]){
            navigationController.tabBarItem.title = @"关注";
            navigationController.tabBarItem.image = [UIImage imageNamed:@"tab_location_normal"];
            navigationController.tabBarItem.selectedImage = [UIImage imageNamed:@"tab_location_selected"];
            navigationController.tabBarItem.tag = 5002;
        }
        if([controller isMemberOfClass:[WGMeViewController class]]){
            navigationController.tabBarItem.title = @"我的";
            navigationController.tabBarItem.image = [UIImage imageNamed:@"tab_user_normal"];
            navigationController.tabBarItem.selectedImage = [UIImage imageNamed:@"tab_user_selected"];
            navigationController.tabBarItem.tag = 5003;
        }
    }else{
        //视图控制器
        if([controller isMemberOfClass:[WGPublishViewController class]]){
            controller.tabBarItem.title = @"发布";
            controller.tabBarItem.image = [UIImage imageNamed:@"tab_cart_normal"];
            controller.tabBarItem.selectedImage = [UIImage imageNamed:@"tab_cart_selected"];
            controller.tabBarItem.tag = 5004;
        }
        [tabBarController addChildViewController:controller];
    }
}

///返回制定大小与颜色的UIImage对象
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    if (!color ||
        size.width <= 0 ||
        size.height <= 0) return nil;
    
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size,NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

#pragma mark -- UITabBarControllerDelegate

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if(viewController.tabBarItem.tag == 5003){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"你是过不去的" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
            NSLog(@"Top YES Button");
        }];
        [alert addAction:yesAction];
        [self.window.rootViewController presentViewController:alert animated:true completion:nil];
        return NO;
    }else{
        return YES;
    }
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    //如果点击了新帖
    if(viewController.tabBarItem.tag == 5001){
        //隐藏标签栏项的标记值
        viewController.tabBarItem.badgeValue = nil;
        //记录点击的新帖控制器
        self.controller = viewController;
    }else{
        //点击的不是新帖控制器时,恢复新帖标签项的标记值
        self.controller.tabBarItem.badgeValue = @"5";
    }
}

@end

Copy the code

The style is shown as follows: