UIBarButtonItem在用作左侧或右侧导航栏项目时,自定义视图未在iOS 7上正确对齐 [英] UIBarButtonItem with custom view not properly aligned on iOS 7 when used as left or right navigation bar items

查看:152
本文介绍了UIBarButtonItem在用作左侧或右侧导航栏项目时,自定义视图未在iOS 7上正确对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码通过iOS 6运行:

The following code works up through iOS 6:

UIButton *myButton = nil;
myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.bounds = CGRectMake(0,0,44,30);
// setup myButton's images, etc.

UIBarButtonItem *item = nil;
item = [[UIBarButtonItem alloc] initWithCustomView:customButton];

这是按钮的对齐方式:

但是,在iOS 7上,按钮似乎从右侧或左侧偏移了太多像素:

However, on iOS 7, the button appears to be offset from the right or left by too many pixels:

如何让自定义条形按钮项目正确对齐?

How can I get my custom bar button items to be aligned properly?

推荐答案

为了解决这个问题,你必须对UIButton进行子类化,以便你可以覆盖 alignmentRectInsets 。根据我的测试,您需要返回具有正向右偏移或正向左偏移的UIEdgeInsets,具体取决于按钮位置。这些数字对我来说没有任何意义(根据常识,它们中至少有一个应该是负数),但这实际上是有效的:

In order to fix this bug, you must subclass UIButton so that you can override alignmentRectInsets. From my testing, you'll need to return a UIEdgeInsets with either a positive right offset or a positive left offset, depending on the button position. These numbers make no sense to me (at least one of them should be negative, according to common sense), but this is what actually works:

- (UIEdgeInsets)alignmentRectInsets {
    UIEdgeInsets insets;
    if (IF_ITS_A_LEFT_BUTTON) {
        insets = UIEdgeInsetsMake(0, 9.0f, 0, 0);
    } 
    else { // IF_ITS_A_RIGHT_BUTTON
        insets = UIEdgeInsetsMake(0, 0, 0, 9.0f);
    }
    return insets;
}

特别感谢@zev建议我尝试调整alignmentRectInsets。

Special thanks to @zev for suggesting I try adjusting alignmentRectInsets.

这篇关于UIBarButtonItem在用作左侧或右侧导航栏项目时,自定义视图未在iOS 7上正确对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆