ios-realization of home tabbar and sliding hide NavBar and Tabbar

Source: Internet
Author: User

Before doing the live broadcast, the reference to the Customer app, found that the effect of its homepage is quite good, in the Internet to find a bit of the relevant imitation Guest app code and blog, most of them are said how to play live stream and push stream, for the UI this piece very little, so I spent a bit of time to study the home UI effect.

Reproduced from SUN's BLOG-focus on Internet knowledge, share the spirit of the Internet!.

The main part of the home is divided into two parts, the implementation of no text and the middle button prominent, and the TabBar other part is to show sliding ScrollView hide and display NavBar and TabBar . Let's take a slow look.

First, Tabbar realization

First, let's look at the effect after implementation.

Mirror bottom Tabbar effect

Here we can use the system TabBar to achieve this effect.

about how to set up the system TabBar , here will not repeat, you can see the code of my project. Let's take a look at the highlights.

1. Ask questions:
    1. How to implement the middle highlight button
    2. The middle Highlight button exceeds TabBar the part of how the click is answered
    3. How to implement a TabBar Item picture centered without text

(1) Middle Highlight button

To implement the middle prominent button, the direct use of the system TabBar or not, you need to use a trickery method, through KVC the way ( using KVC can modify readonly properties, but can not abuse oh ) using a custom TabBar replacement system UITabBar .

//创建自己的tabbar,然后用KVC将自己的tabbar和系统的tabBar替换下HKTabBar *tabbar = [[HKTabBar alloc] init];//KVC实质是修改了系统的_tabBar[self setValue:tabbar forKeyPath:@"tabBar"];

Once you have replaced the system UITabBar , you need to implement the middle button. We add in the customization TabBar UIButton as the middle button.

1. In HKTabBar the initWithFrame: method, initialize the middle button

//设置中间按钮图片和尺寸UIButton *centerBtn = [[UIButton alloc] init];[centerBtn setBackgroundImage:[UIImage imageNamed:@"tab_launch"] forState:UIControlStateNormal];[centerBtn setBackgroundImage:[UIImage imageNamed:@"tab_launch"] forState:UIControlStateHighlighted];//这里button的size是根据需要设置的中间图片来的centerBtn.size = centerBtn.currentBackgroundImage.size;[centerBtn addTarget:self action:@selector(centerBtnDidClick) forControlEvents:UIControlEventTouchUpInside];self.centerBtn = centerBtn;[self addSubview:centerBtn];

2. layoutSubviews set the middle button and other Item positions in
Because the system Item is a UITabBarButton type, the custom middle button is UIutton , so you can Item differentiate between a custom button or a system based on the type, and Item then adjust each Item position. The width UITabBarButton TabBar of the system is less than half the width of the middle button.

//系统自带的按钮类型是UITabBarButton,找出这些类型的按钮,然后重新排布位置,空出中间的位置Class class = NSClassFromString(@"UITabBarButton");self.centerBtn.centerX = self.centerX;//调整中间按钮的中线点Y值self.centerBtn.centerY = (self.height - (self.centerBtn.height - self.height)) * 0.5;NSInteger btnIndex = 0;for (UIView *btn in self.subviews) {//遍历tabbar的子控件    if ([btn isKindOfClass:class]) {//如果是系统的UITabBarButton,那么就调整子控件位置,空出中间位置        //按钮宽度为TabBar宽度减去中间按钮宽度的一半        btn.width = (self.width - self.centerBtn.width) * 0.5;        //中间按钮前的宽度,这里就3个按钮,中间按钮Index为1        if (btnIndex < 1) {            btn.x = btn.width * btnIndex;        } else { //中间按钮后的宽度            btn.x = btn.width * btnIndex + self.centerBtn.width;        }        btnIndex++;        //如果是索引是0(从0开始的),直接让索引++,目的就是让消息按钮的位置向右移动,空出来中间按钮的位置        if (btnIndex == 0) {            btnIndex++;        }    }}[self bringSubviewToFront:self.centerBtn];

In this case, the middle button is OK, but how do you let the out TabBar -of-the-box (that is, the red frame part) respond to the Click event?

Tabbar Center button Highlight position

(2) More than Tabbar partial response click

According to the system default processing mode, out of the TabBar section, will not respond to the Click event (do not believe you can try it yourself OH). To respond to a click event, you need to override UIView the hitTest: method (which determines the responder of the Click event).

//重写hitTest方法,去监听中间按钮的点击,目的是为了让凸出的部分点击也有反应- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {    //判断当前手指是否点击到中间按钮上,如果是,则响应按钮点击,其他则系统处理    //首先判断当前View是否被隐藏了,隐藏了就不需要处理了    if (self.isHidden == NO) {        //将当前tabbar的触摸点转换坐标系,转换到中间按钮的身上,生成一个新的点        CGPoint newP = [self convertPoint:point toView:self.centerBtn];        //判断如果这个新的点是在中间按钮身上,那么处理点击事件最合适的view就是中间按钮        if ( [self.centerBtn pointInside:newP withEvent:event]) {            return self.centerBtn;        }    }    return [super hitTest:point withEvent:event];}

After finishing the outstanding part, there is no text left Item .

(3) The item picture in Tabbar is centered without text

Some students may say, or with text, not set tabBarItem the title good. But this is also the title NavBar title to use, so it must be set.

What do we do then? In fact, to achieve this effect, the following code is enough

//设置图片居中,这里的4.5,根据实际中间按钮图片大小来决定Vc.tabBarItem.imageInsets = UIEdgeInsetsMake(4.5, 0, -4.5, 0);//设置不显示文字,将title的位置设置成无限远,就看不到了Vc.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, MAXFLOAT);

Here, TabBar the implementation is over, let's see how to implement hiding and display NavBar and TabBar .

Ii. hiding and displaying NavBar and Tabbar implementations

First, let's take a look at the effect

Swipe to hide NavBar and tabbar effects

1. Ask questions:
    1. How to move NavBar andTabBar
    2. How to control NavBar and TabBar move distances
    3. How to control the area of the ScrollView movement while it is displayed correctly
    4. How to slide the finger at a distance of less than an hour, to close up or unfold NavBar andTabBar
    5. How on Push to other pages, Pop and then come back, NavBar and show the TabBar right

First of all, we have to solve the most basic problem, how to make NavBar and TabBar move

(1) Mobile NavBar and Tabbar

Moving words, in fact, is very simple, just need to change their y-coordinate.

//这里的self就是NavBar或者TabBarCGRect viewFrame = self.frame;viewFrame.origin.y = newOffsetY;self.frame = viewFrame;

(2) Control NavBar and Tabbar moving distance

The moving distance depends on ScrollView the relative moving distance, that is, contentOffset.y how much has been slid relative to the previous slide.

Before we calculate the relative moving distance, we need to get the last slide, and ScrollView contentOffset.y we can get the last swipe in, that - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView ScrollView contentOffset.y is _previousOffsetY ,

_previousOffsetY = scrollView.contentOffset.y;

After the implementation ScrollView of the delegate method - (void)scrollViewDidScroll:(UIScrollView *)scrollView , in which to listen to ScrollView the moving distance, thus calculating the relative moving distancedeltaY

CGFloat deltaY = scrollView.contentOffset.y - _previousOffsetY;

After we get the relative moving distance, we need to control NavBar TabBar the moving distance separately.
Here, we can implement a classification to specifically control their movement.

Note that when the relative distance exceeds the range to be moved, it needs to be corrected
So, we must first know NavBar and TabBar the upper and lower bounds of the coordinates, that is, its expansion and the coordinates of the collection Y , the following code openOffsetY is the expanded Y coordinates, closeOffsetY for the closed Y coordinates.

//NavBar//kStatusBarHeight为状态栏高度openOffsetY = kStatusBarHeight;closeOffsetY = -CGRectGetHeight(self.frame;//TabBar//kScreenHeight为屏幕宽度,hk_extraDistance为中间按钮突出的距离openOffsetY = kScreenHeight - CGRectGetHeight(self.frame);closeOffsetY = kScreenHeight + CGRectGetHeight(self.frame) + self.hk_extraDistance;

The coordinates are all Y coordinates, and we're only moving in the vertical direction.
Once you know the range that can be moved, you can calculate the moved coordinates based on the relative moving distance deltaY .
for NavBar , the computed coordinates (that is, the current coordinate minus deltaY ) are larger than the closed coordinates less than the expanded coordinates.
for TabBar the computed coordinates (that is, the current coordinate plus), the coordinates that are deltaY larger than the expanded coordinate are less than the closed coordinates.
Drawing pictures here will be a good understanding of some.

//NavBar最终要移动的Y坐标newOffsetY = CGRectGetMinY(self.frame) - deltaY;newOffsetY = MAX(closeOffsetY, MIN(openOffsetY, newOffsetY));//TabBar最终要移动的Y坐标newOffsetY = CGRectGetMinY(self.frame) + deltaY;newOffsetY = MIN(closeOffsetY, MAX(openOffsetY, newOffsetY));

After that, just drag NavBar and TabBar move to the specified coordinates

CGRect viewFrame = self.frame;viewFrame.origin.y = newOffsetY;self.frame = viewFrame;

Let's see ScrollView how the movement is controlled.

(3) control enables the ScrollView to move while its display area is correct

Careful children's shoes may be found, when NavBar the process of unwinding or unfolding, ScrollView is moving along with each other, that is, ScrollView itself does not slide, but Y the coordinates are changing. How does that work?

Here, we can change ScrollView contentInset to meet our needs, relative to ScrollView the change is much more frame convenient oh.

We have to base and NavBar TabBar move the coordinates after the change of the ScrollView contentInset top and bottom .
topIs the height of the NavBar MaxY current Y coordinate plus itself.
bottomThe TabBar highlight distance, which is the screen height minus the Y portion whose coordinates are greater than 0.
Here to note: ScrollView The scrollIndicatorInsets same time also need to update, or Indicator display there is a problem.

CGFloat navBarMaxY = CGRectGetMaxY(self.navigationController.navigationBar.frame);CGFloat tabBarMinY = CGRectGetMinY(self.tabBarController.tabBar.frame);UIEdgeInsets scrollViewInset = self.tableView.contentInset;scrollViewInset.top = navBarMaxY;scrollViewInset.bottom = MAX(0, kScreenHeight - tabBarMinY);self.tableView.contentInset = scrollViewInset;self.tableView.scrollIndicatorInsets = scrollViewInset;

(4) in the finger sliding distance of less than the hour, the NavBar and Tabbar

Careful children's shoes may find that, when the sliding distance is smaller, sometimes NavBar and TabBar will bounce back, sometimes will be put up. How is this done?

This needs to be handled when the slide is stopped, and we can handle it in ScrollView the delegate method - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate .
To determine the current NavBar or TabBar sliding distance, slide to half of the maximum coordinate (the maximum coordinate minus the minimum coordinate). If there is no slide, then it is closed and the other is expanded. This might be a bit more around, let's look at the code.

//判断当前`NavBar`是展开还是收起- (BOOL)hk_shouldOpen {    CGFloat viewY = CGRectGetMinY(self.frame);    //[self hk_openOffsetY]为展开的Y坐标,[self hk_closeOffsetY] 为收起的Y坐标    CGFloat viewMinY = [self hk_openOffsetY];    viewMinY = [self hk_closeOffsetY] + ([self hk_openOffsetY] - [self hk_closeOffsetY]) * 0.5;    if (viewY <= viewMinY) {        return NO;    }    return YES;}

When you know it's expanded or closed, you can slide it. Here we do a simple animation, so that the slide looks natural, here in addition to change ScrollView contentInset , but also need to change it contentOffset , because NavBar and TabBar moved, ScrollView but also to move along with.

[UIView animateWithDuration:0.2 animations:^{    CGFloat navBarOffsetY = 0;    if (opening) {        //navBarOffsetY为NavBar从当前位置到展开滑动的距离        navBarOffsetY = [self.navigationController.navigationBar hk_open];        [self.tabBarController.tabBar hk_open];    } else {        //navBarOffsetY为NavBar从当前位置到收起滑动的距离        navBarOffsetY = [self.navigationController.navigationBar hk_close];        [self.tabBarController.tabBar hk_close];    }    //更新TableView的contentInset    [self updateScrollViewInset];    //根据NavBar的偏移量来滑动TableView    CGPoint contentOffset = self.tableView.contentOffset;    contentOffset.y += navBarOffsetY;    self.tableView.contentOffset = contentOffset;}];

(5) After push to other pages, and then pop back, NavBar and Tabbar display correctly

Pushbefore you go to another page, you have to put it in and out, or it will be NavBar in the TabBar closed state Push to the other pages, NavBar and TabBar all are gone.
It needs to be - (void)viewWillDisappear:(BOOL)animated unfolded in both the Admiral NavBar and the TabBar .

There is one more place to note:
When you Push go to another page, if this ScrollView is contentInset not the (0,0,0,0) case, the system will automatically set it (0,0,0,0) , so that Push after, will go to the previous page ScrollView scrollViewDidScroll: method, will cause the NavBar disappearance. In this case, it should not be allowed to continue our process of processing expansion and collection NavBar TabBar .
We can control it with the following code, and UIViewController UIViewController not go down when it is not currently displayed.

//在push到其他页面时候,还是会走该方法,这个时候不应该继续执行if (!(self.isViewLoaded && self.view.window != nil)) {   return;}

Here, the effect of the homepage of the Mirror is achieved!

Demo Project

The Demo project address: Https://github.com/HustHank/YingKeHomeDemo

If you feel that this article is useful to you, please help me to like or Star my GitHub project, thank you!

Turn from: Hk_hank

Reproduced from SUN's BLOG-focus on Internet knowledge, share the spirit of the Internet!

ios-realization of home tabbar and sliding hide NavBar and Tabbar

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.