码迷,mamicode.com
首页 > 移动开发 > 详细

iOS关于自定义rightBarButtonItem

时间:2016-05-29 16:32:35      阅读:580      评论:0      收藏:0      [点我收藏+]

标签:

在常见iOS开发中,我们常遇到这样的需求,如下:

技术分享

我们需要自定义导航栏右侧按钮,常见的自定义包装按钮如下:

    //设置rightItem;

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

    btn.frame = CGRectMake(0, 0, 40, 30);

    btn.selected = NO;

    [btn setTitle:@"管理" forState:UIControlStateNormal];

    [btn setTitle:@"取消" forState:UIControlStateSelected];

    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [btn addTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:btn];

    [self.navigationItem setRightBarButtonItem:rightItem];

    但通过这个方法,我们往往是不能调整自定义出来的UIview距离屏幕边界的方法,对于一些比价坑*的产品经理来说,这远远不能达不到他们那颗装*的心,这个时候我们只能通过如下方法来调整整个个customView距离右边边界的值:

//设置rightBarBtnItem样式:

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

    btn.frame = CGRectMake(0, 0, 100, 30);

    [btn setImage:[UIImage imageNamed:@"rightUp"] forState:UIControlStateNormal];

    [btn setTitle:@"推荐奖励" forState:UIControlStateNormal];

    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];

    btn.titleLabel.font = [UIFont systemFontOfSize: 15.0];

    btn.titleLabel.textAlignment = NSTextAlignmentRight;

    [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];

    UIBarButtonItem *rewardItem = [[UIBarButtonItem alloc]initWithCustomView:btn];

    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];

    spaceItem.width = -15;

    [btn addTarget:self action:@selector(pushToReward) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.rightBarButtonItems = @[spaceItem,rewardItem];

注意:这里着重强调的是给rightBarButtonItems弄成了一个数组,给它增加了一个spaceItem元素,用来控制customView距离右边的间距,本身rightBarButtonItem中包装的button距离它父控件,也就是rightBarButtonItem的值是5,当我们把width设置为-15后,相当于把整个rightBarButtonItem向右移动了10,对于特殊需求,可自行去调整.

iOS关于自定义rightBarButtonItem

标签:

原文地址:http://www.cnblogs.com/shineDongEr/p/5539545.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!