2

I have weird problem, because I can't fill whole area of super view using layout anchor

this is my code from custom UIView class:

   private func setupTableView() {
            addSubview(tableView)
            tableView.translatesAutoresizingMaskIntoConstraints = false

            let margins = layoutMarginsGuide

            let trailingAnchor = tableView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
            let leadingAnchor = tableView.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
            let topAnchor = tableView.topAnchor.constraint(equalTo: margins.topAnchor)
            let bottomAnchor = tableView.bottomAnchor.constraint(equalTo: margins.bottomAnchor)

            NSLayoutConstraint.activate([trailingAnchor, leadingAnchor, topAnchor, bottomAnchor])
}

and in result I get weird margins on the left and right site:

enter image description here

Robert
  • 3,790
  • 1
  • 27
  • 46

1 Answers1

3

You are laying out your tableView relative to the margins of the layoutMarginsGuide. If you want it to go to the edges of your UIView, then you need to use the anchors of the UIView:

private func setupTableView() {
    addSubview(tableView)
    tableView.translatesAutoresizingMaskIntoConstraints = false

    let trailingAnchor = tableView.trailingAnchor.constraint(equalTo: trailingAnchor)
    let leadingAnchor = tableView.leadingAnchor.constraint(equalTo: leadingAnchor)
    let topAnchor = tableView.topAnchor.constraint(equalTo: topAnchor)
    let bottomAnchor = tableView.bottomAnchor.constraint(equalTo: bottomAnchor)

    NSLayoutConstraint.activate([trailingAnchor, leadingAnchor, topAnchor, bottomAnchor])
}
vacawama
  • 150,663
  • 30
  • 266
  • 294