A. K. M. Tariqul Islam
A. K. M. Tariqul Islam

Reputation: 2834

Background image for each cell

I want to create an UITableView where each cell will have a background image and so far I am doing this:

//UITableViewController
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("HomeTVCell", forIndexPath: indexPath)

    // Configure the cell...
    cell.textLabel?.text = StaticData.HOME_ITEMS_TEXT[indexPath.row]
    cell.textLabel?.backgroundColor = UIColor(white: 1, alpha: 0)
    imageView = UIImageView(frame: cell.frame);
    imageView.image = UIImage(named: StaticData.HOME_ITEMS_IMGS[indexPath.row])
    cell.backgroundView = UIView()
    cell.backgroundView?.addSubview(imageView)

    NSLog("Row: \(indexPath.row), Img: \(StaticData.HOME_ITEMS_IMGS[indexPath.row])")

    return cell
}

And StaticData contains:

static let HOME_ITEMS_TEXT = [
    "Get Inspired",
    "Places & Attractions",
    "Foods",
    "Tourist Map",
    "Recommended Tours",
    "Tips: Save Money",
    "Tips: Comfort",
    "Hotels",
    "Emergency",
    "Tourism Companies",
    "Travel Companies"
]

static let HOME_ITEMS_IMGS = [
    "AhsanMonzil",
    "AhsanMonzil",
    "AhsanMonzil",
    "AhsanMonzil",
    "AhsanMonzil",
    "AhsanMonzil",
    "AhsanMonzil",
    "AhsanMonzil",
    "AhsanMonzil",
    "AhsanMonzil",
    "AhsanMonzil"
]

But I'm only getting background image for the first cell. What am I missing?

Upvotes: 1

Views: 79

Answers (2)

Joe Huang
Joe Huang

Reputation: 6560

call cell.layoutIfNeeded() before return cell

Upvotes: 0

Justlike
Justlike

Reputation: 1504

Replace code of below:

cell.backgroundView = UIView()
cell.backgroundView?.addSubview(imageView)

with:

cell.backgroundView = imageView;

Upvotes: 2

Related Questions