开发者

Turn off highlighting on UIBarButtonItem

I'm trying to use a UIBarButtonItem to put a title on my UIToolbar. I'm using the plain style and that looks fine, but I can't seem to get it to stop highlighting on touch. The Sho开发者_如何转开发ws Touch When Highlighted option isn't available for the bar button items. Is there a quick and easy way to do this? I'm trying to do the building in interface builder so I can see what I'm doing. I'd prefer not to build the toolbar in the view did load every time.


The property responsible for this is accessible in the UIButton class:

myButton.showsTouchWhenHighlighted = NO;

You can access this (programmatically) in a UIBarButtonItem by assigning a UIButton to the bar button item's customView property, and configuring the button. You can do this in Interface Builder too: drag a UIButton onto a UIToolbar, and it will automatically embed it in a UIBarButtonItem for you - then look for the "Shows Touch On Highlight" checkbox under the button's settings.

Incidentally, I don't know how you're customising your buttons so feel free to ignore this, but if your button looks and behaves like a standard toolbar item then users will expect the glow effect.


I wanted a solution that could be used without any modification to my XIB structure.
The most obvious and simple one worked: subclass UIBarButtonItem:

UITitleBarButtonItem.h:

//
//  UITitleBarButtonItem.m
//  Created by Guillaume Cerquant - MacMation on 09/08/12.
//

/*
 * A UIBarButtonItem that does not show any highlight on the touch
 * Drag and drop a normal UIBarButtonItem in your xib and set its subclass to UITitleBarButtonItem
 */
@interface UITitleBarButtonItem : UIBarButtonItem
@end

UITitleBarButtonItem.m:

#import "UITitleBarButtonItem.h"

@implementation UITitleBarButtonItem

// Only caring about UITitleBarButtonItem set up in Interface Builder. Update this class if you need to instantiate it from code

- (void) awakeFromNib {
    UIView *theView = [self valueForKey:@"view"];

    if ([theView respondsToSelector:@selector(setUserInteractionEnabled:)]) {
        theView.userInteractionEnabled = NO;
    }
}

@end

Tested on iOS 5 and the one we aren't allowed to talk yet.


Alternative: Use a UIBarButtonItem in the plain style and additionally cover the toolbar in the appropriate area with a UIView that has a clear background. The view consumes the taps and hides them from the bar button item. Make sure you set the autoresizing mask correctly.


My solution was to set it to disabled, and adjust the titleAttributes for each UIControlState

let attributes: [NSAttributedStringKey: Any] = [
    .font: UIFont.boldSystemFont(ofSize: 16),
    .foregroundColor: UIColor.white
]

barButton.setTitleTextAttributes(attributes, for: .enabled)
barButton.setTitleTextAttributes(attributes, for: .disabled)
barButton.isEnabled = false
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜