button控制视图的隐藏与显示

来源:互联网 发布:ted baker 知乎 编辑:程序博客网 时间:2024/06/05 08:27

在同一位置设置按钮的切换,同时伴随着对应页面的跳转,在平时经常会遇到。这里重点实现按钮的隐藏和显示效果,特意理一下思路。欢迎交流分享。

实现按钮的切换效果。这里按钮设置在导航栏的左侧:

代码:

- (void) _createNavigationRightItem {

    

    //父视图

    UIView *customView = [[UIViewalloc] initWithFrame:CGRectMake(0, 0, 49, 32)];

    customView.backgroundColor = [UIColorclearColor];

    customView.tag = 1000;

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItemalloc] initWithCustomView:customView];

    

    //两个子视图

    UIButton *postButton = [UIButtonbuttonWithType:UIButtonTypeCustom];

    [postButton setImage:[UIImageimageNamed:@"poster_home"]forState:UIControlStateNormal];

    [postButton setBackgroundImage:[UIImageimageNamed:@"exchange_bg_home@2x"]forState:UIControlStateNormal];

    postButton.frame = customView.bounds;

    postButton.tag = 1001;

    postButton.hidden = YES;

    [postButton addTarget:selfaction:@selector(rightAction:)forControlEvents:UIControlEventTouchUpInside];

    [customView addSubview:postButton];

    

    

    UIButton *listButton = [UIButtonbuttonWithType:UIButtonTypeCustom];

    [listButton setImage:[UIImageimageNamed:@"list_home"]forState:UIControlStateNormal];

    [listButton setBackgroundImage:[UIImageimageNamed:@"exchange_bg_home@2x"]forState:UIControlStateNormal];

    listButton.frame = customView.bounds;

    listButton.tag = 1002;

    listButton.hidden = NO;

    [listButton addTarget:selfaction:@selector(rightAction:)forControlEvents:UIControlEventTouchUpInside];

    [customView addSubview:listButton];

}

设置好一个父视图,将下一步要添加的按钮放上去,需要两个按钮来实现它的切换效果。这里一共创建了三个视图,分别设置好了背景和图片,而且设置了tag值。按钮的点击事件响应在同一个方法里面。

接下来我们要实现它的点击事件:

- (void)rightAction:(UIButton *) btn {

    

//获取对应视图tag值

    UIButton *btn1 = [self.navigationController.navigationBarviewWithTag:1001];

    UIButton *btn2 = [self.navigationController.navigationBarviewWithTag:1002];

    UIView *view = [self.navigationController.navigationBarviewWithTag:1000];

    

    UIViewAnimationOptions option;

    BOOL flip = btn1.hidden;

    

//button的切换效果设置

    if (flip ) {

//翻转效果

        option = UIViewAnimationOptionTransitionFlipFromLeft;

    } else {

        option = UIViewAnimationOptionTransitionFlipFromRight;

    }

    

//***button的隐藏和显示

    [UIView transitionWithView:view duration:0.35options:option animations:^{

        btn1.hidden = !btn1.hidden;

        btn2.hidden = !btn2.hidden;

        

    } completion:NULL];

    

//页面的隐藏和显示(两个视图页面可以自己创建,这里就不显示了)

    [UITableView transitionWithView:listViewduration:0.35 options:optionanimations:^{

        listView.hidden = !listView.hidden;

        postView.hidden = !postView.hidden;

        

    } completion:NULL];

    

}


需要注意的是一定要记得调用方法,对两个按钮的切换和隐藏一定要思路清晰。




0 0