将您的标签设置为向右对齐文本:
var timeLabel: UILabel = {
let label = UILabel()
label.backgroundColor = .clear
label.textColor = .gray
label.textAlignment = .right
label.font = UIFont.systemFont(ofSize: 15, weight: .bold)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
现在在 viewDidLoad 中将标签添加到导航栏并设置约束:
if let navigationBar = self.navigationController?.navigationBar {
timeLabel.text = "FRIDAY, SEPTEMBER 18" // set here your string date
navigationBar.addSubview(timeLabel)
timeLabel.leadingAnchor.constraint(equalTo: navigationBar.leadingAnchor, constant: 150).isActive = true // set the constant how do you prefer
timeLabel.trailingAnchor.constraint(equalTo: navigationBar.trailingAnchor, constant: -20).isActive = true
timeLabel.bottomAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: 0).isActive = true
timeLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
表格视图滚动更新
将 UIScrollViewDelegate 添加到您的控制器,然后像这样实现 scrollViewWillBeginDragging 和 tableView willDisplay 方法:
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if scrollView.contentSize.height > 0 && ((scrollView.contentOffset.y + scrollView.safeAreaInsets.top) == 0) {
timeLabel.alpha = 0
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if tableView.contentOffset.y <= 0 {
timeLabel.alpha = 1
}
}
奖金
当timeLabel再次显示时,在tableView中添加动画效果会很酷,就像这样:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if tableView.contentOffset.y <= 0 {
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut) {
self.timeLabel.alpha = 1
} completion: { (_) in
print("visible TimeLabel")
}
}
}
这是结果
吉尔更新
上面解释的不是规则而是一个技巧,我建议您考虑将日期放在标题中,这样您就不会再遇到标题问题:删除scrollViewWillBeginDragging和tableView willDisplay函数并添加viewForHeaderInSection,这样做删除现有的 timeLabel 约束并声明 viewForHeaderInSection:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let v = UIView()
v.backgroundColor = UIColor(red: 0.9018846154, green: 0.9020112157, blue: 0.9018446803, alpha: 1)
v.addSubview(timeLabel)
// declare here your timeLabel constraints
timeLabel.topAnchor.constraint(equalTo: v.topAnchor).isActive = true
timeLabel.trailingAnchor.constraint(equalTo: v.trailingAnchor).isActive = true
timeLabel.leadingAnchor.constraint(equalTo: v.leadingAnchor).isActive = true
timeLabel.bottomAnchor.constraint(equalTo: v.bottomAnchor).isActive = true
return v
}
现在设置标题的高度:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
结果如下: