OriginalAlchemist
OriginalAlchemist

Reputation: 411

Swift : Different UIView in each UITableView cell

I am simply trying to get a different UIView to appear in each cell. So i do this:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


    let cell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell

    cell.textLabel?.text = self.items[indexPath.row]

    if(indexPath.row == 0){

        print("Index path shold be 0 : \(indexPath.row)")

        maleIcon = MaleIconView(frame: CGRect(x: 0, y: 0, width: 55, height: 55))
        maleIcon.center.x = cell.center.x + cell.center.x * 0.5
        maleIcon.center.y = cell.contentView.center.y
        maleIcon.layer.cornerRadius = 0.5 * maleIcon.bounds.size.width
        cell.addSubview(maleIcon)

    }
    else if(indexPath.row == 1){
        //Next UIView(different from one above) will go here
    }


    return cell

}

I have a total of 12 cells. The UIView will appear in the correct cell at first, but if you keep scrolling down the same UIView will appear in a different cell, then scroll back up the UIView will be gone and from here it just goes all over the screen. Please please please help! I have to get this app out today!!

Upvotes: 0

Views: 774

Answers (1)

Lumialxk
Lumialxk

Reputation: 6369

It's so bad to addSubview in your data source.Because of reuse,views will create many times.The solution is make two type cells with different identifier in your storyboard.And then add the MaleIconView in your storyboard(it will call init(coder:) function,please override that).

Another solution is in your custom cell prepareForReuse(),remove MaleIconView.You don't need to create a new cell for this.

I looked over your codes.You should set gender for your cell in func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

More elegant solution is use a static table view instead,this will make it easy.

Upvotes: 1

Related Questions