当前,当滚动表内容时,headerLabel
跟随滚动并停留在顶部。如何通过自动版式避免这种行为?
var tableView: UITableView!
let headerLabel: UILabel = {
let label = UILabel(frame: .zero)
label.font = UIFont.boldSystemFont(ofSize: 34.0)
label.textColor = .black
label.textAlignment = .center
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
tableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: view.frame.width, height: view.frame.height - barHeight))
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "tableCell")
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .none
view.addSubview(headerLabel)
view.addSubview(tableView)
headerLabel.snp.makeConstraints { (make) in
make.top.equalTo(view).offset(35)
make.width.equalToSuperview()
}
tableView.snp.makeConstraints { (make) in
make.top.equalTo(headerLabel.snp.bottom)
make.left.bottom.right.equalToSuperview()
}
}
headerLabel
应该与tableView
一起滚动,并且看起来不像是粘性标头。
答案 0 :(得分:2)
答案 1 :(得分:0)
当前,您的表视图和标签是UIViewController视图内的兄弟姐妹,这意味着您的标签不属于表视图,因此它不会滚动。您可以将标签添加到UIView,设置其约束,然后设置表视图的tableHeaderView
属性。这是带有一些硬编码值的示例代码:
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "some text"
label.sizeToFit()
let headerView = UIView()
headerView.translatesAutoresizingMaskIntoConstraints = false
headerView.addSubview(label)
tableView.tableHeaderView = headerView
headerView.centerXAnchor.constraint(equalTo: tableView.centerXAnchor).isActive = true
headerView.heightAnchor.constraint(equalToConstant: 80).isActive = true
headerView.widthAnchor.constraint(equalTo: tableView.widthAnchor).isActive = true
label.leftAnchor.constraint(equalTo: headerView.leftAnchor, constant: 50).isActive = true
tableView.tableHeaderView?.layoutIfNeeded()