Cesare
Cesare

Reputation: 9419

Sizing of table view cell and table view header view

I have a table view which displays table view cells and a header view (search bar). I want the width of the table view cells to be 0.9 of the device screen size, and the header view to have the same size. However, this is not possible because cells and the header view are all contained in a table view.

When I use layout anchor constraints everything gets resized (including the header view).

self.tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true

// here's the 0.9 multiplier
self.tableView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.9).isActive = true
self.tableView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
self.tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0).isActive = true

How can I make sure that the table view header has the same width of the view controller, while keeping the table view width to be 0.9 of the main view?

Upvotes: 1

Views: 507

Answers (2)

dmorrow
dmorrow

Reputation: 5664

It is best not to try to adjust the constraints of a TableViewCell or its contentView. However, you can just set both those views to have a background color of .clear and then add subviews to the contentView with the constraints you want.

class CustomCell: UITableViewCell {

    let smallerView = UIView()
    override init(frame: CGRect) {
        super.init(frame)
        smallerView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(smallerView)
        smallerView.widthAnchor.contraint(equalTo: contentView.widthAnchor, multiplier: 0.9).isActive = true
        smallerView.heightAnchor.contraint(equalTo: contentView.heightAnchor).isActive = true
    }
}

Upvotes: 2

DonMag
DonMag

Reputation: 77462

Your custom cell "starts with" a ContentView, which uses uses the table view's insets to set its width...

So, if you have a bunch of elements / objects that you are adding to the content view...

Your best bet is to probably first add a standard UIView as a "container view"... (just my naming of it)...

Then, set the constraints on that "containing view" to be 0.9 of the width of the contentView...

All of the elements you add to that "containing view" will be constrained relative to it and thus will all stay inside the 0.9-width overall...

Upvotes: 1

Related Questions