Reputation: 77
This code works fine ONLY when i sroll through my table view but the first cell that loads and appear are not taking the needed colors. I tried to call the func in CellforRowAt and CellWillDisplayAt and both had the same effect
And what is driving me crazy is that the backgroundview takes the colors correctly, But the Button title color only takes effect for the first cells upon scrolling and the code of view and button are implemented in same func
The class extensions where i load my cell from a XIB file
extension MyPlansTableViewCellPresenter : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! MyPlansTableViewCell
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let newcell = cell as! MyPlansTableViewCell
newcell.setCellColors(index: indexPath.row)
//This code works fine ONLY when i sroll through my table view but the first cell that loads and appear are not taking the needed colors.
}
}
My cell is designed in a XIB file and loaded there and here is the Class of it
class MyPlansTableViewCell: UITableViewCell {
@IBOutlet weak var renewBtn: UIButton!
@IBOutlet weak var upgradePlanBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
public func setCellColors(index: Int){
if index % 2 == 0 {
upgradePlanBtn.titleLabel?.textColor = .TextColor
holderView.backgroundColor = .TextColor
} else if index % 2 == 1 {
upgradePlanBtn.titleLabel?.textColor = .systemYellow
holderView.backgroundColor = .systemYellow
}
}
Upvotes: 0
Views: 54
Reputation: 109
try this !!
public func setCellColors(index: Int){
if index % 2 == 0 {
upgradePlanBtn.setTitleColor(.TextColor, for: .normal)
holderView.backgroundColor = .TextColor
} else if index % 2 == 1 {
upgradePlanBtn.setTitleColor(.systemYellow, for: .normal)
holderView.backgroundColor = .systemYellow
}
You have to specify the state of the button in the code using this code
upgradePlanBtn.setTitleColor(.systemYellow, for: .normal)
Upvotes: 1
Reputation: 1239
It will work if you set color inside draw function
override func draw(_ rect: CGRect) {
super.draw(rect)
//Your code here
}
Upvotes: 0