更改图像视图图标Swift的颜色

时间:2016-08-06 20:42:17

标签: ios swift cocoa-touch

我正在使用XCode 7.3 for iOS 9.3编写应用程序,并为每个单元格提供一个带有不同图标的菜单。我试图将图标设为白色,因为它们是默认的黑色,但cell!.imageView?.tintColor()似乎没有效果。我可以使用另一种方法吗?

编辑:这是@ LychmanIT建议之后的代码:

  switch indexPath.section {

    case 0: cell?.imageView?.image = UIImage(imageLiteral: "stuff.png")
    case 1: cell?.imageView?.image = UIImage(imageLiteral: "otherstuff.png")
    case 2: cell?.imageView?.image = UIImage(imageLiteral: "menu.png")
    default: cell?.imageView?.image = UIImage(imageLiteral: "error.png")

    }

    cell!.imageView?.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)

    cell!.imageView?.tintColor = UIColor.whiteColor()
编辑:我通过这样做解决了问题:

cell!.imageView?.image! = (cell!.imageView?.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate))!

3 个答案:

答案 0 :(得分:4)

让我们试试这个:

theImageView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
theImageView.tintColor = UIColor.redColor()

答案 1 :(得分:4)

从Swift 3及以上版本开始,此方法成为

func withRenderingMode(_ renderingMode: UIImageRenderingMode) -> UIImage

除了方法名称之外,LychmanIT提出的解决方案对我没有用,因为需要将withRenderingMode方法的返回重新分配给传递给imageView的图像,如:

let newImage = theImageView.image?.withRenderingMode(.alwaysTemplate)
theImageView.image = newImage
theImageView.tintColor = .redColor

关于这个问题,也可以在交换机中运行.withRenderingMode方法,如:

switch indexPath.section {
    case 0: cell?.imageView?.image = UIImage(imageLiteral: "stuff.png").withRenderingMode(.alwaysTemplate)
    case 1: cell?.imageView?.image = UIImage(imageLiteral: "otherstuff.png").withRenderingMode(.alwaysTemplate)
    case 2: cell?.imageView?.image = UIImage(imageLiteral: "menu.png").withRenderingMode(.alwaysTemplate)
    default: cell?.imageView?.image = UIImage(imageLiteral: "error.png").withRenderingMode(.alwaysTemplate)
    }

编辑:

此外,您可以在实用程序窗格中的资产目录 属性检测器中设置图像的渲染模式。< / p>

答案 2 :(得分:1)

imageView.image!.imageWithRenderingMode(.alwaysTemplate)
imageView.tintColor = .red

或者您可以在下面使用扩展名:

import UIKit

extension UIImage {

    func overlayImage(color: UIColor) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
        let context = UIGraphicsGetCurrentContext()

        color.setFill()

        context!.translateBy(x: 0, y: self.size.height)
        context!.scaleBy(x: 1.0, y: -1.0)

        context!.setBlendMode(CGBlendMode.colorBurn)
        let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
        context!.draw(self.cgImage!, in: rect)

        context!.setBlendMode(CGBlendMode.sourceIn)
        context!.addRect(rect)
        context!.drawPath(using: CGPathDrawingMode.fill)

        let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return coloredImage
    }

}