Jac*_* Li 2 cocoa-touch ios swift
我正在为 iOS 9.3 在 XCode 7.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()
Run Code Online (Sandbox Code Playgroud)
编辑:我通过这样做解决了这个问题:
cell!.imageView?.image! = (cell!.imageView?.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate))!
Run Code Online (Sandbox Code Playgroud)
小智 5
让我们试试这个:
theImageView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
theImageView.tintColor = UIColor.redColor()
Run Code Online (Sandbox Code Playgroud)
在 Swift 3 中,这个方法变成了
func withRenderingMode(_ renderingMode: UIImageRenderingMode) -> UIImage
Run Code Online (Sandbox Code Playgroud)
除了方法名称之外,LychmanIT提出的解决方案对我不起作用,因为 withRenderingMode 方法的返回需要重新分配给传递给 imageView 的图像,例如:
let newImage = theImageView.image?.withRenderingMode(.alwaysTemplate)
theImageView.image = newImage
theImageView.tintColor = .redColor
Run Code Online (Sandbox Code Playgroud)
关于这个问题,也可以在switch中运行.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)
}
Run Code Online (Sandbox Code Playgroud)
编辑:
此外,您可以在Utilities窗格中Asset Catalog的 Attribute Instector中设置图像的渲染模式。