1

I'm creating an UIBarbutton item as below

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
}

Tint color is not changing.

If I create simply like

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

Tint color is now changing. But, I need an UIbutton as customview for my barbuttons for some reasons.

How can I change the tintcolor of UIBarbuttonItem with UIbutton as its customview?

Nazik
  • 8,696
  • 27
  • 77
  • 123

2 Answers2

3

You have to instantiate the button using the system type to be able to set the tint color. Then set the tint color to the btn itself.

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

Or, you can force the rendering mode on your UIImage.

btn.setImage(btnImage.withRenderingMode(.alwaysTemplate), for: UIControl.State())
btn.tintColor = .red
Rico Crescenzio
  • 3,952
  • 1
  • 14
  • 28
1
  1. Use image as template image: UIImage(named: "nameOfTheImage")!.withRenderingMode(.alwaysTemplate)
  2. You have to set the buttons tint color if the image is on the button.

    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 }

valentinv
  • 139
  • 5