vishnu
vishnu

Reputation: 233

Contents not showing properly on UITableViewCell

I want to add buttons to a table view cell:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "mycell")

    cell?.backgroundColor = UIColor.clear

    let view2: UIView = UIView()
    view2.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 100)

    view2.backgroundColor = UIColor.white

    cell?.contentView.addSubview(view2)

    prifilebtn = UIButton()
    prifilebtn.frame = CGRect(x: 20, y: (view.bounds.height-60)/2, width: 60, height: 60)
    prifilebtn.layer.cornerRadius = 30
    prifilebtn.clipsToBounds = true
    prifilebtn.backgroundColor = UIColor.red

    view2.addSubview(prifilebtn)

    return cell!
}

The prifilebtn is not showing properly on view which i added to the cell. I am trying to do this programatically. I don' t know what's causing the problem - any help is appreciated. Thanks in advance

enter image description here

Upvotes: 0

Views: 47

Answers (1)

Durdu
Durdu

Reputation: 4859

There are many ways you can customise the UI of your cell. The best way is to subclass UITableViewCell and there are many tutorials on how to do so.

However if you want to avoid subclassing when updating the layout and frames for a cell and its subviews, I believe it is better to handle on the callback for the method:

optional func tableView(_ tableView: UITableView, 
            willDisplay cell: UITableViewCell, 
               forRowAt indexPath: IndexPath)

Upvotes: 1

Related Questions