flu flu - 4 months ago 21
Swift Question

willDisplayCell first row does not work in Swift

I wanted to make custom corner rounded background for my custom cells and it worked with code below but the first row is not affected I should scroll it up to make it have a background

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row != 0 {
cell.contentView.backgroundColor = UIColor.clearColor()
var whiteRoundedCornerView: UIView = UIView(frame: CGRectMake(10, 10, 365, 250))
whiteRoundedCornerView.backgroundColor = UIColor.lightGrayColor()
whiteRoundedCornerView.layer.masksToBounds = false
whiteRoundedCornerView.layer.cornerRadius = 20
whiteRoundedCornerView.layer.shadowOffset = CGSizeMake(-0, -1)
whiteRoundedCornerView.layer.shadowOpacity = 0.1

cell.contentView.addSubview(whiteRoundedCornerView)
cell.contentView.sendSubviewToBack(whiteRoundedCornerView)
}


}

Answer

The issue in your code is the if statement. When indexPath.row is 0 (which is the first row), your configuration code isn't executed. To solve this, simply remove the if statement from your code. It should look something like this:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.contentView.backgroundColor = UIColor.clearColor()
    var whiteRoundedCornerView: UIView = UIView(frame: CGRectMake(10, 10, 365, 250))
    whiteRoundedCornerView.backgroundColor = UIColor.lightGrayColor()
    whiteRoundedCornerView.layer.masksToBounds = false
    whiteRoundedCornerView.layer.cornerRadius = 20
    whiteRoundedCornerView.layer.shadowOffset = CGSizeMake(-0, -1)
    whiteRoundedCornerView.layer.shadowOpacity = 0.1

    cell.contentView.addSubview(whiteRoundedCornerView)
    cell.contentView.sendSubviewToBack(whiteRoundedCornerView)
}