【问题标题】:UIBarButtonItem Highlighted ColorUIBarButtonItem 高亮颜色
【发布时间】:2010-10-25 07:41:28
【问题描述】:

我为UINavigationBar(在UINavigationController 内)设置了一个自定义的色调颜色,这反过来又为插入到UINavigationBar 中的UIBarButtonItems 设置了适当的匹配颜色。但是,当我选择UIBarButtonItem 时,按钮会变为(可能)突出显示状态并呈现不同的颜色,看起来有点过时并且与色调颜色不匹配。有没有办法将此突出显示的状态颜色更改为自定义颜色?

理想情况下,我只想在UIBarButtonItem 上创建一个类别,它会更改UIBarButtonItem 的所有实例的突出显示颜色,因为这样可以避免显式子类化UIBarButtonItems,然后更改我的应用程序中的每个引用使用子类(这会很棘手,因为我正在使用一些只使用 UIBarButtonItem 的第三方库,我不想弄乱它们的实现)。

任何帮助将不胜感激。

【问题讨论】:

    标签: iphone cocoa-touch uikit uinavigationbar uibarbuttonitem


    【解决方案1】:

    据我记得遇到过类似问题,UINavigationBar 只会采用 tintColor 并将 UIBarButtonItem 的颜色设置为更暗(除非样式设置为 BarStyleBlack,在这种情况下它会变成暗灰色)。

    按照您的要求,我将为与您的配色方案匹配的不同控件状态创建一个带有背景图像的自定义 UIButton,然后将此 UIButton 用作自定义 UIBarButtonItem 的视图。

    UIButton *customButton = [UIButton buttonWithType:...];
    
    //normal_button.png and selected_button.png need to be created by you
    [customButton setBackgroundImage: [UIImage imageNamed:@"normal_button.png"] forState:UIControlStateNormal];
    [customButton setBackgroundImage: [UIImage imageNamed:@"selected_button.png"] forState:UIControlStateSelected];
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView: customButton];
    

    如果你想尝试封装它,你总是可以在 UIBarButtonItem 上创建一个工厂或自定义 init 方法(通过一个类别)并使用上面的代码(稍作修改)。

    我知道我并没有完全解决您关于仅使用类别覆盖控制状态的第二点。我不知道在 UIBarButtonItem 中重写什么方法来做这样的事情,但是一旦你发现哪个你想交换的方法。

    我应该注意,我只使用 swizzling 进行测试/调试。

    【讨论】:

    • 你如何设置选中状态? UIBarButton.selected 不存在?那么你将如何访问 UIBarButton 中的 UIButton?
    • 第二张图片必须设置为 UIControlState.Highlighted,而不是 .Selected
    【解决方案2】:

    如果您使用的是 Interface Builder,请将 UIButton 拖放到导航栏右侧,它会作为右侧导航栏按钮项进入。然后,为按钮的不同状态配置不同的色调,就完成了。 适用于 Xcode 10 和 Swift 4。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      相关资源
      最近更新 更多