【发布时间】:2017-12-19 16:32:32
【问题描述】:
我正在使用我创建的 UIImageView 的子类,其中我将其 tintColor 设置为白色:
class UIIconView : UIImageView {
override init(image: UIImage?) {
super.init(image: image)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
self.image = super.image!.withRenderingMode(.alwaysTemplate)
self.tintColor = UIColor.white
}
}
这工作正常,除非我将 UIIconViews 放在 UITableView 的单元格中。当我运行代码并滚动 UITableView 时,白色的 UIIconViews 都变黑了,像这样:
那么,有人知道为什么会这样吗?
PS:我用于图标的原始图像是黑色的,但如果有帮助,我会在 UIIconView 的 layoutSubviews() 中为它们着色。
编辑:
好的,我停止使用 UIImageView 的子类。这是我的整个视图控制器代码,用于这个表视图屏幕:
class MessageCell: UITableViewCell{
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var msgTitle: UILabel!
@IBOutlet weak var msgText: UILabel!
}
class MessagesListViewController: UITableViewController {
let mockMessages = ["Msg1", "Msg2", "Msg3", "Msg4", "Msg5", "Msg6", "Msg7", "Msg8", "Msg9"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mockMessages.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath) as! MessageCell
cell.msgTitle.text = mockMessages[indexPath.row]
cell.msgText.text = mockMessages[indexPath.row]
cell.icon.image = UIImage(named: "ic_email_48pt")
cell.icon.tintColor = UIColor.white
cell.backgroundColor = UIColor.clear
return cell
}
}
【问题讨论】:
-
显示你的
cellForRow方法 -
我不建议为此子类化
UIImageView。将代码从layoutSubviews()移出到表视图委托的cellForRowAt方法。 -
layoutSubviews应该只用于更新视图的子视图的框架。它不应该用于其他任何事情。您当前在layoutSubviews中的代码只能在init方法中调用一次。并且当你覆盖它时总是调用super.layoutSubviews。 -
@the4kman 好的,用更多信息编辑了我的问题。
-
@rmaddy 感谢您提供的信息。我不再继承 UIImageView 来改变它的颜色。
标签: ios swift uitableview uiimageview