Is it possible to use AutoLayout with UITableView's tableHeaderView?

前端 未结 29 1417
醉梦人生
醉梦人生 2020-11-28 19:51

Since I discovered AutoLayout I use it everywhere, now I\'m trying to use it with a tableHeaderView.

I made a subclass of

29条回答
  •  猫巷女王i
    2020-11-28 20:28

    The following worked for me.

    1. Use a plain old UIView as the header view.
    2. Add subviews to that UIView
    3. Use autolayout on the subviews

    The main benefit I see is limiting frame calculations. Apple should really update UITableView's API to make this easier.

    Example using SnapKit:

    let layoutView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 60))
    layoutView.backgroundColor = tableView.backgroundColor
    tableView.tableHeaderView = layoutView
    
    let label = UILabel()
    layoutView.addSubview(label)
    label.text = "I'm the view you really care about"
    label.snp_makeConstraints { make in
        make.edges.equalTo(EdgeInsets(top: 10, left: 15, bottom: -5, right: -15))
    }
    

提交回复
热议问题