Search code examples
iosswiftuibuttonuibarbuttonitemtint

Change tintcolor of UIBarButton with UIButton as its customview


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?


Solution

  • 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