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;
对齐内容。虽然内容向右移动,但可点击区域仍处于中间位置。
答案 0 :(得分:0)
试试这个:
y
并使用如下:
public extension UIView {
//From iOS 11 -> UIBarButtonItem uses autolayout instead of dealing with frames. so adding contraint for the barbuttonItem
public func applyNavBarConstraints(size: (width: CGFloat, height: CGFloat)) {
if #available(iOS 11.0, *) {
let widthConstraint = self.widthAnchor.constraint(equalToConstant: size.width)
let heightConstraint = self.heightAnchor.constraint(equalToConstant: size.height)
heightConstraint.isActive = true
widthConstraint.isActive = true
}
}}
这对我有用。希望这有帮助!