我正在创建一个自定义视图,它需要是可点击的,因此是按钮,需要在导航栏的左侧(所以,我替换了leftBarButtonItem)。
如果我将自定义视图添加到带有 - (id)initWithCustomView:(UIView *)customView;的UIBarButtonItem,则放置正是我想要的,但我无法“点击”它。如果我将自定义视图添加为UIButton子视图,并使用UIBarButtonItem中的按钮 - (id)initWithCustomView:(UIView *)customView;我可以点击它,但现在我的cusotm视图有大约26点的topmargin,超过了navigationBar高度。
这个位置正确,但无法点击
UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
....
UIBarButtonItem *customButton = [[UIBarButtonItem alloc] initWithCustomView:customView];
self.navigationItem.leftBarButtonItem = customButton;
这个位置错误,但可以点击它
UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
....
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addSubview:customView];
[button addTarget:self action:@selector(userProfile) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = customButton;
希望我已经说清楚了。我对这真的很无能为力。我已经尝试在UIButton中强制使用imageEdgeInsets,修改框架“y”原点使其为负...但没有任何效果。
编辑:@kschaeffer解决方案有效。只需要将按钮框设置为与customView框架相同。这不再适用于iOs 7
在这种情况下,它会获得一个不需要的左边距,并且停止可点击(就我所见,按钮没有记录触摸事件)
答案 0 :(得分:1)
尝试将customButton框架设置为与自定义视图相同。这实际上适合我。
UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
UIButton *customButton = [[UIButton alloc] initWithFrame:customView.bounds];
[customButton addTarget:target action:@selector(userProfile) forControlEvents:UIControlEventTouchUpInside];
[customView addSubview:customButton];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:customView];
self.navigationItem.rightBarButtonItem = customItem;