关闭UIBarButtonItem上的高亮显示

7

我正在尝试使用UIBarButtonItem在UIToolbar上显示标题。使用纯样式看起来很好,但是我似乎无法停止触摸高亮。对于工具栏按钮,没有“显示触摸时高亮”的选项。有没有快速简便的方法来解决这个问题?我正在试图在Interface Builder中构建以便于查看。我希望不必每次在视图加载中构建工具栏。

4个回答

3

负责此功能的属性可在UIButton类中访问:

myButton.showsTouchWhenHighlighted = NO;

您可以通过将UIButton分配给UIBarButtonItem的customView属性,并配置该按钮,在UIBarButtonItem中以编程方式访问此内容。您也可以在Interface Builder中执行此操作:将UIButton拖放到UIToolbar上,它将自动嵌入到UIBarButtonItem中 - 然后在按钮设置下查找“显示触摸高亮”复选框。
顺便提一下,我不知道您如何自定义您的按钮,所以请随意忽略此信息,但是如果您的按钮看起来和行为像标准的工具栏项,那么用户将期望出现发光效果。

这个按钮本身只是一个标题。我只需要一个工具栏,这样我就可以有一堆按钮了,而且不知道其他方法如何将标题放在中间。 - codeetcetera
2
@btate:啊,标题。当我需要一个标题时,我实际上只是使用了一个带有适当格式的标准UILabel。也许不像你所做的那样将其嵌入工具栏那么优雅,但可能更简单。如果您感兴趣,这种标签的格式为Helvetica Bold 20.0,白色文本颜色,50%不透明度黑色阴影,垂直偏移量为-1。 - Stuart

2

我希望找到一个能够在不修改我的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上进行测试,以及我们目前还不能谈论的那个版本。


1

替代方案:使用普通样式的UIBarButtonItem,并在适当的区域额外覆盖工具栏,使用具有透明背景的UIView。该视图会消耗点击事件并将其隐藏在条形按钮项中。确保正确设置自动调整大小掩码。


1

我的解决方案是将其设置为禁用,并针对每个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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接