Vadym Marchenko
Vadym Marchenko

Reputation: 29

How I can hide button with size in UITableViewCell cell?

I have UITableView and UITableViewCell. I get data from API. Some items have a link, others have not. If the item has not to link I wand to hide button with a book icon. When I use this method (look below) button is hidden right, but then when the tableview reuse this cell icon with a book does not come back. How I can fix it?

var addButtonTrailingConstraint =  openPdfButton.widthAnchor.constraint(equalToConstant: 0)
    if link == nil{
        NSLayoutConstraint.activate([addButtonTrailingConstraint])


    }else{
         NSLayoutConstraint.deactivate([addButtonTrailingConstraint])
    }

}

enter image description here

Upvotes: 0

Views: 226

Answers (2)

2h4u
2h4u

Reputation: 513

This is kinda hard to answer without more code / knowledge of your constraint setup.

But I can give you 2 tips how to solve this issue by taking another approach:

1. Approach: Use UIStackView to manage your buttons:

Remove your buttons and replace them with a UIStackView. Then in code, where you config your cell (set text, title, ...) you first remove all Buttons from the UIStackView (you can do this easily with stackView.removeAllArrangedSubviews(), this is needed because the cells are getting reused and you don't want to add more and more buttons every time the cell is getting displayed. After that, add the buttons you need in this cell (e.g.: like this: stackView.addArrangedSubview(button)).

This approach has the benefit that it is very dynamic, you can add as many different buttons as you wish without having to modify your code. But since you need to create new buttons all the time it is not the most performance efficient solution.

2. Approach: Use 2 different UITableViewCell classes:

Make 2 different UITableViewCells, one with one button and a second one with 2 buttons. You can also inherit one from another to reduce duplicate code. Then in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) check which one of the 2 cell classes you need, create the right one and set its members (text, title, ...).

This approach is less flexible but more performance efficient in comparison to the 1. approach. I use both approaches in production and they are working quite nicely :)

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100541

You need

if link == nil {
     openPdfButton.widthAnchor.constraint(equalToConstant: 0).isActive = true 
} else { 
     openPdfButton.constraints.forEach {
       openPdfButton.removeConstraint($0)
     }
}

Upvotes: 1

Related Questions