【发布时间】:2017-11-28 10:38:33
【问题描述】:
UIButton *rideButton = [UIButton buttonWithType:UIButtonTypeCustom];
rideButton.titleLabel.font = CUSTOM_BUTTON_FONT;
[rideButton setTitleColor:[UIColor CUSTOM_BUTTON_TITLE_COLOR1] forState:UIControlStateNormal];
[rideButton setTitleColor:[UIColor CUSTOM_BUTTON_TITLE_COLOR2] forState:UIControlStateHighlighted];
[rideButton setTitle:@"Ride" forState:UIControlStateNormal];
[rideButton addTarget:self action:@selector(rideButtonClicked) forControlEvents:UIControlEventTouchUpInside];
CGSize s1 = [rideButton.titleLabel.text sizeWithFont:rideButton.titleLabel.font];
rideButton.frame = (CGRect) {
.size.width = (s1.width+rideBarButtonGap)>100?100:(s1.width+rideBarButtonGap),
.size.height = s1.height + rideBarButtonGap
};
rideButton.backgroundColor = [UIColor redColor];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 11.0)
{
[[rideButton.widthAnchor constraintEqualToConstant:rideButton.frame.size.width] setActive:YES];
[[rideButton.heightAnchor constraintEqualToConstant:rideButton.frame.size.height] setActive:YES];
}
UIBarButtonItem *rideBarButton= [[UIBarButtonItem alloc] initWithCustomView:rideButton];
self.navigationItem.rightBarButtonItem = rideBarButton;
这是我创建自定义 UIBarButtonItem 的代码。我将背景颜色设置为红色只是为了查看按钮的边界。背景颜色在文本之外看起来很完美,但我无法正确单击按钮。只有在选择“RI”时才会触发按钮的操作。如果选择了“de”,则不调用该函数。它只发生在 iOS 11 中。我添加了宽度和高度限制来解决这个问题,但没有任何变化。
编辑:
当我增加 widthAnchor 的宽度时,我能够实现我想要的,但是按钮向左移动并且按钮和屏幕之间有很多间隙。所以我尝试使用rideButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight; 对齐内容。虽然内容向右移动,但可点击区域仍在中间。
【问题讨论】:
-
你想要达到什么样的最终结果?
-
我想在触摸 Ride 时调用该函数,但只有在触摸 'Ri' 时才会调用它。
标签: ios uibarbuttonitem ios11