nothingtonil
nothingtonil

Reputation: 33

tableview addsubview to custom cell

How to add a UISwitch using addsubview to a specific section and row of tablview?

For example:

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 12
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }


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

        var oneObject = UISwitch(frame: CGRect(x: 260, y: 5, width: 50, height: 30)) as UISwitch

        if indexPath.section == 2 && indexPath.row == 0
        {
            oneObject.tag = 8
            cell.contentView.addSubview(oneObject)
        }

        return cell
    }

This tableview will keep adding to a random cell when scrolling.

Upvotes: 1

Views: 2973

Answers (1)

NRitH
NRitH

Reputation: 13893

cellForRowAtIndexPath should be used only to set properties of a cell, not add or remove subviews. Since the cell gets reused for every table row (in your example, anyway), adding the switch in one call winds up affecting all rows, even at random-seeming times. A better approach is to add the UISwitch to the prototype cell, and then hide or show it in cellForRowAtIndexPath.

Upvotes: 2

Related Questions