简体   繁体   中英

UIBarButtonItem action selector ios11

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;

This is my code to create custom UIBarButtonItem. I have set the background color to red just to see the bounds of the button. The background color looks perfectly outside the text but I'm unable to click the button properly. The button's action get fired only when 'Ri' is selected. If 'de' is selected, the function is not called. It happens only in iOS 11. I have added width and height constraints to fix this but there is no change.

EDIT: When I increase the width of widthAnchor, I'm able to acheive what I want but the button moves left and theres lot of gap between the button and Screen. So I tried to align the content using rideButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight; . Though the content moves right, the clickable area is still in the middle.

Try this:

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
    }
}}

and use it as below:

rideBarButton.applyNavBarConstraints(size: (width: 50, height: 44)) //expected height and width

This works for me. Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM