Add a UIButton as a subview to a UITabBar

2019-01-20 09:35发布

问题:

I am trying to implement a hideable UITabBar in my app. I've set up all the animations, and they work very well. I'm just having an issue getting my UIButton "pull-tab" to show the tab bar. It is not responding to the touch event UIControlEventTouchUpInside. I add the pull-tab to the UITabBar in the UITabBarController:

- (void)viewDidLoad
{
    [super viewDidLoad];
//Add pull
    pullButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image = [UIImage imageNamed:@"TabBarPull.png"];
    pullButton.frame = CGRectMake(self.tabBar.frame.size.width - image.size.width, -image.size.height + 3, image.size.width, image.size.height);
    [pullButton setImage:image forState:UIControlStateNormal];
    [pullButton addTarget:self action:@selector(pullBarTapped:) forControlEvents:UIControlEventTouchUpInside];
    pullButton.userInteractionEnabled = YES;
    [self.tabBar addSubview:pullButton];
}

Here is what the tab bar looks like open and closed:

Edit: I've determined that the problem is because the button falls outside the UITabBar's frame. Looks like I'm going to have to put the button outside of the UITabBar... Animation nightmare.

回答1:

You can still add the UIButton to the UITabBarController's main view, not in the UITabBar though.... [myUITabBarController.view addSubview:pullButton]



回答2:

Since you have the hiding part working within the UITabbar and from the answer i have seen here, one alternative would be to keep the UIButton within the UITabbar but also add the button to the view when the UITabbar is hidden (so you will have two button that overlay). When the tabbar is displayed hide the button you have added to the view using the hidden property on the view.