UI基础iOS学习交流iOS干货

navigationItem上按钮和屏幕边界的间距

2016-04-05  本文已影响2963人  7dfa9c18c1d1

调整navigationItem上leftBarButtonItem和rightBarButtonItem与屏幕边界的间距
我们的项目中可能会碰见这样的需求:需要我们设置navigationItem上leftBarButtonItem和rightBarButtonItem与屏幕边界的间距,可是这些不是系统都默认设置好的嘛?我们能改吗?
我们当然可以更改,需要用到这个常量UIBarButtonSystemItemFixedSpace

**UIBarButtonSystemItemFixedSpace:指定固定间距值时,使用 UIBarButtonSystemItemFixedSpace; UIBarButtonSystemItemFlexibleSpace: 能自动调节按钮间的间距(这个我用的少,感觉没有上面那个固定值的好用) **

    UIView *leftBarView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH/2, 44)];
    leftBarView.backgroundColor = [UIColor greenColor];

    UIBarButtonItem *leftBtnItem = [[UIBarButtonItem alloc]initWithCustomView:leftBarView];
    self.navigationItem.leftBarButtonItem = leftBtnItem;

    //解决UIBarButtonItem偏移
    UIBarButtonItem *negativeSeperator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSeperator.width = -20;
    // 注意下面这个顺序不要写错了,写错了顺序会导致写不出我们想要的效果
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSeperator,leftBtnItem,nil];

    UIView *right = [[UIView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH/3, 44)];
    right.backgroundColor = [UIColor orangeColor];

    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc]initWithCustomView:right];
    self.navigationItem.rightBarButtonItem = rightBtnItem;

    //解决UIBarButtonItem偏移
    UIBarButtonItem *negativeSeperator2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSeperator2.width = -20;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSeperator2,rightBtnItem,nil];
这样就可以了

注意两点:1是上面数组中的顺序不要写错。2是-20的距离是笔者自己尝试出来的,正常的系统按钮就是距离屏幕-20距离

来张效果图

Simulator Screen Shot 2016年4月5日 15.51.25.png
上一篇下一篇

猜你喜欢

热点阅读