【问题标题】:Change tintcolor of UIBarButton with UIButton as its customview使用 UIButton 作为自定义视图更改 UIBarButton 的 tintcolor
【发布时间】:2019-12-04 17:42:39
【问题描述】:

我正在创建一个 UIBarbutton 项,如下所示

func createNavigationButton(_ btnImage: UIImage, btnAction: Selector) -> UIBarButtonItem {
    let btn = UIButton()
    btn.setImage(btnImage, for: UIControl.State())
    btn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    btn.addTarget(self, action: btnAction, for: .touchUpInside)
    let item = UIBarButtonItem()
    item.customView = btn
    item.tintColor = .red
    return item
}

色调颜色不变。

如果我像这样简单地创建

let item = UIBarButtonItem.init(image: btnImage,
                                    style: .plain,
                                    target: self,
                                    action: btnAction)
item.tintColor = .red

色调颜色现在正在改变。但是,出于某些原因,我需要一个 UIbutton 作为我的 barbuttons 的自定义视图。

如何以 UIbutton 作为其自定义视图来更改 UIBarbuttonItem 的 tintcolor?

【问题讨论】:

  • 你试过btn.tinitColor 吗?
  • 检查这个答案:stackoverflow.com/questions/27539067/…,可能会有所帮助
  • @PrashantTukadiya,是的,我为 btn 尝试了 tintcolor。它不工作
  • @Kampai,这是一个不同的问题。与色调无关。
  • 导航栏的barTintColor怎么样?

标签: ios swift uibutton uibarbuttonitem tint


【解决方案1】:
  1. 使用图像作为模板图像:UIImage(named: "nameOfTheImage")!.withRenderingMode(.alwaysTemplate)
  2. 如果图像在按钮上,您必须设置按钮的色调。

    func createNavigationButton(_ btnImage: UIImage, btnAction: Selector) -> UIBarButtonItem { let btn = UIButton() btn.setImage(btnImage, for: UIControl.State()) btn.frame = CGRect(x: 0, y: 0, width: 30, height: 30) btn.addTarget(self, action: btnAction, for: .touchUpInside) btn.tintColor = .red let item = UIBarButtonItem() item.customView = btn item.tintColor = .red return item }

【讨论】:

    【解决方案2】:

    您必须使用system 类型实例化按钮才能设置色调颜色。然后将 tint 颜色设置为 btn 本身。

    let btn = UIButton(type: .system)
    btn.tintColor = .red
    

    或者,您可以在 UIImage 上强制呈现模式。

    btn.setImage(btnImage.withRenderingMode(.alwaysTemplate), for: UIControl.State())
    btn.tintColor = .red
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-23
      • 2018-05-22
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多