I am trying to calculate table header height based on constraints. When I use the property layoutMarginsGuide, I get the wrong size causing it systemLayoutSizeFittingSize. If I click the edges without using the guide field, it works.
Here is the code:
class SomeVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
let tableView = UITableView()
let headerView = UIView()
let circle = UIView()
let circleSize: CGFloat = 100
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellID")
view.addSubview(tableView)
headerView.layoutMargins = UIEdgeInsetsMake(20, 20, 20, 20)
headerView.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.36)
circle.backgroundColor = UIColor.grayColor()
circle.layer.cornerRadius = circleSize/2
headerView.addSubview(circle)
let margins = headerView.layoutMarginsGuide
circle.translatesAutoresizingMaskIntoConstraints = false
circle.topAnchor.constraintEqualToAnchor(margins.topAnchor).active = true
circle.bottomAnchor.constraintEqualToAnchor(margins.bottomAnchor).active = true
circle.centerXAnchor.constraintEqualToAnchor(margins.centerXAnchor).active = true
circle.widthAnchor.constraintEqualToConstant(circleSize).active = true
circle.heightAnchor.constraintEqualToConstant(circleSize).active = true
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
tableView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true
tableView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true
tableView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true
let size = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
headerView.frame = CGRect(origin: CGPointZero, size: size)
tableView.tableHeaderView = headerView
let size2 = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
print("size:", size.height)
print("size2:", size2.height)
}
}
Why, when I call the systemLayoutSizeFittingSizesecond time, it gives the correct size?
source
share