Amir_P Amir_P - 1 year ago 90
Swift Question

Changing color of a view in tableview cell doesn't make change

I'm changing background colour of a view in

but it doesn't change at first load and i need to scroll to see changes. This is my cell class:

@IBOutlet weak var status_back: UIView!
@IBOutlet weak var status_label: UILabel!
@IBOutlet weak var node_label: UILabel!
@IBOutlet weak var time_label: UILabel!
@IBOutlet weak var name_label: UILabel!
@IBOutlet weak var res_date: UILabel!

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

override func awakeFromNib() {

override func layoutSubviews() {
status_back.layer.cornerRadius = status_back.frame.height/2

and the code that changes color of status_back in ViewController:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "MealCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ReservationCell
let reservation = filteredreservations[(indexPath as NSIndexPath).row]
cell.name_label.text = "نام: "+reservation.client_name
cell.name_label.font = UIFont(name: "WeblogmaYekan", size: 17)
cell.time_label.text="زمان: "+reservation.ft_of_time+"-"+reservation.ft_to_time
cell.time_label.font = UIFont(name: "B Yekan", size: 17)
cell.res_date.text="تاریخ: \("
cell.res_date.font = UIFont(name: "B Yekan", size: 17)
var status = ""
if reservation.type {
cell.node_label.text="ex1 \(reservation.node_title)"
} else {
switch reservation.res_status {
case "CanceledByAdmin":
cell.status_back.backgroundColor=Utils.UIColorFromRGB(rgbValue: 0xFFFC635D)
status = "ex"
case "Canceled":
cell.status_back.backgroundColor=Utils.UIColorFromRGB(rgbValue: 0xFFEE903D)
status = "ex"
case "Deprecated":
cell.status_back.backgroundColor=Utils.UIColorFromRGB(rgbValue: 0xFF757575)
status = "ex"
cell.status_back.backgroundColor=Utils.UIColorFromRGB(rgbValue: 0xFF3BA757)
status = "ex"
cell.status_label.font = UIFont(name: "WeblogmaYekan", size: 17)
return cell

Answer Source

I've found the answer. when cell is created there is no data for status_back.frame.height so

override func layoutSubviews() {
    status_back.layer.cornerRadius = status_back.frame.height/2

makes status_back invisible and the next time it recycled the code works

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download