IOS project-custom UITabBar and layout, ios custom uitabbar

Source: Internet
Author: User

IOS project-custom UITabBar and layout, ios custom uitabbar

In the previous articleIOS project-Basic Framework ConstructionThe following describes how to customize the image attributes and text attributes of TabBarItem. However, in many cases, we need to modify the image and text attributes of TabBarItem and customize the position of TabBarItem. In this way, the style of the built-in TabBar cannot meet our project requirements, therefore, we need to customize the UITabBar to meet our project requirements. For example, the item of the tab at the bottom of the Sina Weibo App cannot be implemented using the built-in TabBarItem. The [+] microblog publishing at the very middle is not used to switch the tab, instead, it overwrites an editing and publishing page on the current page. After the release is completed or canceled, it returns to the previous page without switching. At this time, we need to customize the TabBar, place the [+] release button in the space of a TabBar in the middle.

Our project is to learn and improve the functional modules of the "best practices" App. Its TabBar style is basically similar to that of Weibo (such as the picture on the right ), the most intermediate Tab button is also a posting function. It overwrites an editing and publishing page on the current page. After publishing is completed or canceled, it returns to the previous page without switching.

· Solution

There are two solutions for this situation, similar to Sina Weibo and our project:

  • Define five tabbaritemsAnd then add a release button in the middle of the TabBar and a click event on the TabBarItem. In this way, because the size is equal, the new button completely overwrites the TabBarItem in the middle, the response event of the most intermediate TabBarItem will also be blocked, because the button will first respond
  • Custom TabBar, Override its layoutSubviews method, modify the layout and size of all four tabbaritems, empty the middle, and then add a custom [release] button to achieve its click event.
1. Overwrite controls

The idea of this solution has been mentioned above, that is, to take a place first and then overwrite it with a button. The main drawback is that it is a waste to apply for a location and a controller to occupy space.Only applicable when the size of each control is evenWhen the specifications and sizes of each TabBarItem are different, we cannot use this solution.

There are several points worth noting:

  • Set the text attribute of all UITabBarItem in the previous articleIOS project-Basic Framework ConstructionAs mentioned in, I will not detail it here
  • [Release] button initialization should use Singleton mode to createBecause there is only one release button in our project, it is more reasonable to use the singleton mode. This article uses the lazy loading method to create the singleton mode.
  • In viewWillAppear:, add the [Publish] button [self. tabBar addSubview: self. publishButton];. Why should I add the publish button in viewWillAppear: instead of viewDidLoad?The root cause is that the TabBarItem is loaded to the TabBar and executed after viewDidLoad.Therefore, if you add the publish button in viewDidLoad, the publish button will be the first to be added in the TabBar. As a result, the publish button will be overwritten by TabBarItem, in this way, we can achieve our goal.
# Import "XMGTabBarController. h "@ interface XMGTabBarController ()/** intermediate release button */@ property (nonatomic, strong) UIButton * publishButton; @ end @ implementation XMGTabBarController # pragma mark-initialization-(void) viewDidLoad {[super viewDidLoad]; /***** set the text attribute of all UITabBarItem *****/UITabBarItem * item = [UITabBarItem appearance]; // NSMutableDictionary * normalAttrs = [NSMutableDictionary dictionary]; norm AlAttrs [NSFontAttributeName] = [UIFont systemFontOfSize: 14]; normalAttrs [identifier] = [UIColor grayColor]; [item setTitleTextAttributes: normalAttrs forState: UIControlStateNormal] // NSMutableDictionary * selectedAttrs = [NSMutableDictionary dictionary]; selectedAttrs [encoding] = [UIColor darkGrayColor]; [item setTitleTextAttributes: normalAttrs ForState: UIControlStateSelected];/***** Add sub-controller *****/[self setupOneChildViewController: [[UITableViewController alloc] init] title: @ "essence" image: @ "tabBar_essence_icon" selectedImage: @ "Courier"]; [self setupOneChildViewController: [[UITableViewController alloc] init] title: @ "" image: @ "tabBar_new_icon" selectedImage: @ "tabBar_new_click_icon"]; // The subcontroller used for placeholder in the middle [self setupOneChildViewCon Troller: [[UIViewController alloc] init] title: nil image: nil selectedImage: nil]; [self setupOneChildViewController: [[UIViewController alloc] init] title: @ "follow" image: @ "tabBar_friendTrends_icon" selectedImage: @ "alert"]; [self setupOneChildViewController: [[UITableViewController alloc] init] title: @ "I" image: @ "tabBar_me_icon" selectedImage: @ "tabBar_me_click_icon"];}/*** why is it in v IewWillAppear: How do I add the publish button to the method? * When viewWillAppear: The method is called, five uitabbarbuttons * have been added to the tabBar to achieve the following effect: the [Publish button] is placed on another UITabBarButton */-(void) viewWillAppear :( BOOL) animated {[super viewWillAppear: animated];/***** Add a release button *****/[self. tabBar addSubview: self. publishButton] ;}# pragma mark-lazy loading/** publish button */-(UIButton *) publishButton {if (! _ PublishButton) {_ publishButton = [UIButton buttonWithType: UIButtonTypeCustom]; _ publishButton. backgroundColor = XMGRandomColor; [_ publishButton setImage: [UIImage imageNamed: @ "success"] forState: Success]; [_ publishButton setImage: [UIImage imageNamed: @ "success"] forState: UIControlStateHighlighted]; _ publishButton. frame = CGRectMake (0, 0, self. tabBar. frame. size. width/5, self. tabBar. frame. size. height); _ publishButton. center = CGPointMake (self. tabBar. frame. size. width * 0.5, self. tabBar. frame. size. height * 0.5); [_ publishButton addTarget: self action: @ selector (publishClick) forControlEvents: UIControlEventTouchUpInside];} return _ publishButton ;} # pragma mark-listener/*** click the publish button */-(void) publishClick {XMGLogFunc XMGTestViewController * test = [[XMGTestViewController alloc] init]; [self presentViewController: test animated: YES completion: nil];} @ end
2. Custom TabBar

Custom TabBar can layout and configure the attributes and layout of each sub-control in TabBar according to our requirements.

@ Interface XMGTabBarController () @ end @ implementation XMGTabBarController # pragma mark-initialization-(void) viewDidLoad {[super viewDidLoad]; /***** set the text attributes of all UITabBarItem ***** // omit/***** Add sub-controller *****/[self setupOneChildViewController: [[UITableViewController alloc] init] title: @ "essence" image: @ "tabBar_essence_icon" selectedImage: @ "Courier"]; [self setupOneChildViewController: [[UITableViewController alloc] init] title: @ "New Post" image: @ "tabBar_new_icon" selectedImage: @ "tabBar_new_click_icon"]; [self setupOneChildViewController: [[UIViewController alloc] init] title: @ "follow" image: @ "tabBar_friendTrends_icon" selectedImage: @ "alert"]; [self setupOneChildViewController: [[UITableViewController alloc] init] title: @ "I" image: @ "tabBar_me_icon" selectedImage: @ "tabBar_me_click_icon"];/***** change TabBar *****/[self setValue: [[XMGTabBar alloc] init] forKeyPath: @ "tabBar"];} @ end

The following code defines the TabBar. the main content of the m file is to overwrite the layoutSubviews method. In this method, we adjusted the size and layout of the four buttons, then add a publish button in the middle. Likewise, there are several points to note:

  • [Release] The button Initialization is the same as above. The single-instance mode should be used for initialization;
  • When rewriting the layoutSubviews method, you should first call this method of the parent class [super layoutSubviews]; in this way, you can first layout the TabBarItem and then adjust the layout based on this layout.The statements that call the parent layout method cannot be placed behind them, and cannot be omitted.This method has many other configurations besides TabBarItem layout;
  • Use self. subviews to obtain the current Child control. We can print out the type and quantity of the current Child control first, and then filter out the control to be modified for layout, we generally use the KVC method to obtain and modify the table. For example, we have modified the current TabBar [self setValue: [[XMGTabBar alloc] init] forKeyPath: @ "tabBar"];, for details about how to obtain attributes and member variables, see:Three minutes to teach you how to get attributes and member variables in runtime
# Import "XMGTabBar. h "@ interface XMGTabBar ()/** intermediate release button */@ property (nonatomic, weak) UIButton * publishButton; @ end @ implementation XMGTabBar # pragma mark-lazy loading/** release button */-(UIButton *) publishButton {if (! _ PublishButton) {UIButton * publishButton = [UIButton buttonWithType: UIButtonTypeCustom]; publishButton. backgroundColor = XMGRandomColor; [publishButton setImage: [UIImage imageNamed: @ "success"] forState: Success]; [publishButton setImage: [UIImage imageNamed: @ "success"] forState: Success]; [publishButton addTarget: self action: @ selector (publi ShClick) forControlEvents: UIControlEventTouchUpInside]; [self addSubview: publishButton]; _ publishButton = publishButton;} return _ publishButton ;} # pragma mark-initialization/*** layout sub-control */-(void) layoutSubviews {[super layoutSubviews]; /***** set the frame size of all uitabbarbuttons ***** // CGFloat buttonW = self. frame. size. width/5; CGFloat buttonH = self. frame. size. height; CGFloat buttonY = 0; // button index int buttonIn Dex = 0; for (UIView * subview in self. subviews) {// filter out non-UITabBarButton // if (! [@ "UITabBarButton" isw.tostring: NSStringFromClass (subview. class)]) continue; if (subview. class! = NSClassFromString (@ "UITabBarButton") continue; // set frame CGFloat buttonX = buttonIndex * buttonW; if (buttonIndex> = 2) {// two UITabBarButton buttonX + = buttonW;} subview. frame = CGRectMake (buttonX, buttonY, buttonW, buttonH); // Add the index buttonIndex ++ ;} /***** set the frame of the intermediate release button *****/self. publishButton. frame = CGRectMake (0, 0, buttonW, buttonH); self. publishButton. center = CGPointMake (self. frame. size. width * 0.5, self. frame. size. height * 0.5) ;}# pragma mark-listener-(void) publishClick {XMGLogFunc} @ end
3 add a red dot prompt

Currently, many App tabbaritems have a red dot prompt in the upper right corner when there is a new message, and some even have a specific number of reminders, similar to our commonly used QQ, Weibo, and toutiao.com, this prompt is calledBadge(In fact, they are generally named like this ). In iOS, TabBarItem comes with this property and control. We can configure it as needed. It is the configuration document in iOS11, which allows you to customize the number and color of prompts, you can also configure the properties of the prompt text in different States.

It is said that the color of the badge prompt cannot be configured before iOS10. At this time, if necessary, we can only customize TabBarItem and then configure the custom badge. This article does not elaborate on this point. If you need it, you can seek help from your friends.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.