【发布时间】:2011-05-06 19:51:08
【问题描述】:
我正在尝试使用 UIBarButtonItem 在我的 UIToolbar 上放置标题。我使用的是朴素的风格,看起来不错,但我似乎无法让它停止在触摸时突出显示。 “突出显示时显示触摸”选项不适用于条形按钮项目。有没有一种快速简便的方法来做到这一点?我正在尝试在界面生成器中进行构建,以便我可以看到我在做什么。我不想在每次都加载的视图中构建工具栏。
【问题讨论】:
我正在尝试使用 UIBarButtonItem 在我的 UIToolbar 上放置标题。我使用的是朴素的风格,看起来不错,但我似乎无法让它停止在触摸时突出显示。 “突出显示时显示触摸”选项不适用于条形按钮项目。有没有一种快速简便的方法来做到这一点?我正在尝试在界面生成器中进行构建,以便我可以看到我在做什么。我不想在每次都加载的视图中构建工具栏。
【问题讨论】:
可以在UIButton 类中访问负责此操作的属性:
myButton.showsTouchWhenHighlighted = NO;
您可以通过将 UIButton 分配给条形按钮项的 customView 属性并配置按钮,在 UIBarButtonItem 中访问它(以编程方式)。您也可以在 Interface Builder 中执行此操作:将 UIButton 拖到 UIToolbar 上,它会自动为您将其嵌入到 UIBarButtonItem 中 - 然后在按钮设置下查找“Shows Touch On Highlight”复选框。
顺便说一下,我不知道您是如何自定义按钮的,因此请随意忽略这一点,但如果您的按钮看起来和行为类似于标准工具栏项,那么用户会期待发光效果。
【讨论】:
我想要一个无需对我的 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
【讨论】: