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

查看:43
本文介绍了带有自定义视图的 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];

按钮应该是这样对齐的:

This is how the button is supposed to be aligned:

但是,在 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天全站免登陆