代码之家  ›  专栏  ›  技术社区  ›  StartPlayer

更改导航栏按钮的颜色

  •  1
  • StartPlayer  · 技术社区  · 8 年前

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

    /// 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 回复  |  直到 8 年前
        1
  •  1
  •   Upholder Of Truth Yawar    8 年前

    直接访问其图像视图的按钮图像属性时始终存在以下问题:

    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方法来设置它。这似乎解决了这个问题。