Rod
Rod

Reputation: 464

UIImageViews turning black when scrolling UITableView

I am using a subclass of UIImageView that I created, in which I set its tintColor to white:

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
    }
}

This is working properly, except when I put UIIconViews inside a cell of a UITableView. When I run the code and scroll through the UITableView, the white UIIconViews all turn black, like this:

UIIconViews turning black when running the app

So, does anyone know why this is happening?

PS: The original image I'm using for the icon is black, but I'm colouring them inside UIIconView's layoutSubviews(), if that helps.

Edit:

Ok, I stopped using the subclass of UIImageView. Here's my whole view controller code, for this table view screen:

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
    }
}

Upvotes: 1

Views: 108

Answers (1)

Rod
Rod

Reputation: 464

As @the4kman and @rmaddy recommended, I'm no longer subclassing UIImageView to change its color. Instead, I'm doing that inside the cellForRowAt method of my view controller and now it works.

Upvotes: 1

Related Questions