首页 文章

更改导航栏按钮的颜色

提问于
浏览
1

我有一种方法来改变图像的颜色 . 我在我的应用程序的菜单中快速使用此颜色图标,而无需每次都使用正确颜色的任何创建和图像 .

/// Tint an image with a selected colour.
///
/// - Parameters:
///    - image: The image you wish to colour
///    - imageView: The imageView containing the image
///    - colour: Colour you wish to tint image with.  Set as nil if you dont want to change it or im image is multicoloured.
func tint(icon image:UIImage, for imageView:UIImageView,  with colour:UIColor?) {

    if colour != nil {
        let template = image.withRenderingMode(.alwaysTemplate)
        imageView.tintColor = colour!
        imageView.image = template

    } else {
        imageView.image = image
    }

}

这在大多数情况下都可以正常工作 . 但是我的问题是尝试在导航栏中设置图像的颜色,它根本不起作用,图像保持原始颜色 .

我正在尝试以下方式

let dashboardButton = UIButton(type: .custom)

    let dashboardButtonImage = UIImage(named: "example image name")

dashboardButton.setImage(dashboardButtonImage.imageResize(sizeChange: CGSize(width: 20, height: 20)), for: .normal)

    style.tint(icon: dashboardButtonImage, for: dashboardButton.imageView!, with: .red)

    dashboardButton.contentHorizontalAlignment = .fill
    dashboardButton.contentVerticalAlignment = .fill
    dashboardButton.imageView?.contentMode = .scaleAspectFit

    dashboardButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)

    dashboardButton.addTarget(self, action: #selector(ExampleViewController.goToDashboard), for: .touchUpInside)
    let dashboardItem = UIBarButtonItem(customView: dashboardButton)

    self.navigationItem.setRightBarButtonItems([dashboardItem], animated: false)

我可以通过制作正确颜色的图形来轻松解决问题 . 但是,当客户决定要更改颜色时,我想在应用程序中保留这些颜色更改 . 我想知道为什么我不能让它在导航栏中工作?有没有解决这个问题?

1 回答

  • 1

    直接访问其图像视图的按钮图像属性始终存在问题,如下所示:

    buttom.imageView.image = testImage
    

    你可以试试这个而不适合我:

    func tint(icon image: UIImage, for button: UIButton, with colour: UIColor?) {
        if colour != nil {
            let template = image.withRenderingMode(.alwaysTemplate)
            button.setImage(template, for: .normal)
            button.imageView!.tintColor = .red
        } else {
            button.setImage(image, for: .normal)
        }
    }
    

    使用它传递按钮而不是图像视图,函数使用UIButton的setImage方法来设置它 . 这似乎解决了这个问题 .

相关问题