我正在尝试使用UIBarButtonItem在UIToolbar上显示标题。使用纯样式看起来很好,但是我似乎无法停止触摸高亮。对于工具栏按钮,没有“显示触摸时高亮”的选项。有没有快速简便的方法来解决这个问题?我正在试图在Interface Builder中构建以便于查看。我希望不必每次在视图加载中构建工具栏。
负责此功能的属性可在UIButton
类中访问:
myButton.showsTouchWhenHighlighted = NO;
我希望找到一个能够在不修改我的XIB结构的情况下使用的解决方案。
最明显和简单有效的方法是:子类化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
已在iOS 5上进行测试,以及我们目前还不能谈论的那个版本。
替代方案:使用普通样式的UIBarButtonItem,并在适当的区域额外覆盖工具栏,使用具有透明背景的UIView。该视图会消耗点击事件并将其隐藏在条形按钮项中。确保正确设置自动调整大小掩码。
我的解决方案是将其设置为禁用,并针对每个UIControlState
调整titleAttributes
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