javid_davoud
javid_davoud

Reputation: 3

Problem making UIButton in UITableViewCell programmatically

I have a custom cell that requires button in it, but when I enter the code below it makes double buttons.

        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell3", for: indexPath) as! CustomTableViewCell3

        var fram = CGRect(x: 0, y: 0, width: 25, height: 25)
        for counter in 0..<socials.count {
            let ofset = 27.5 * Double(socials.count - 1) - Double(counter * 55) + Double(12.5)
            fram.origin.x = (cell.myView.frame.size.width) / 2 - CGFloat(ofset)
            fram.origin.y = cell.myView.frame.size.height / 4
            fram.size = CGSize(width: CGFloat(25), height: CGFloat(25))
            let socialsButton = UIButton(frame: fram)

            socialsButton.setImage(UIImage(named: "\(Array(socials)[counter].key)Icon"), for: .normal)
            cell.myView.addSubview(socialsButton)

can you please take a look at it

Upvotes: 0

Views: 46

Answers (1)

Catalina T.
Catalina T.

Reputation: 3494

You are adding buttons in a loop - that's why you get more of them. You need to add your button in your custom UITableView class - in your case CustomTableViewCell3. Tableview cells are reused so that code will be executed more than once.

The correct way to do it is something like this:

class CustomTableViewCell3: UITableViewCell { var socialCount: Int! // you can use this as a configuration point for your cell - instead of having the calculation in the cellForRow

override func awakeFromNib() {
    super.awakeFromNib()
        // Calculate the frame here
        let socialsButton = UIButton(frame: frame)

        socialsButton.setImage(UIImage(named: "\(Array(socials)[counter].key)Icon"), for: .normal)
        myView.addSubview(socialsButton)
}

If you need more help, just let me know.

Upvotes: 1

Related Questions