对我来说似乎工作得很好......
class AlphaHeaderTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let vv = UIView()
vv.backgroundColor = .blue
vv.frame.size.height = 60
let v = UILabel()
v.textAlignment = .center
v.text = "Testing"
v.backgroundColor = .green
v.font = UIFont.systemFont(ofSize: 40.0)
v.translatesAutoresizingMaskIntoConstraints = false
vv.addSubview(v)
v.centerXAnchor.constraint(equalTo: vv.centerXAnchor).isActive = true
v.centerYAnchor.constraint(equalTo: vv.centerYAnchor).isActive = true
tableView.tableHeaderView = vv
tableView.tableHeaderView?.alpha = 0.1
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Row \(indexPath.row + 1)"
return cell
}
}
tableView.tableHeaderView?.alpha = 0.1 的结果:
为了比较,结果与tableView.tableHeaderView?.alpha = 1.0:
编辑
当表更新时,tableHeaderView.alpha 属性似乎也被重置了1.0。
要解决这个问题,请将用作标题视图的当前视图嵌入到具有清晰背景的视图中,并设置子视图的.alpha 属性。
例如:
let innerView = UIView()
innerView.backgroundColor = .blue
let vLabel = UILabel()
vLabel.textAlignment = .center
vLabel.text = "Testing"
vLabel.backgroundColor = .green
vLabel.font = UIFont.systemFont(ofSize: 40.0)
vLabel.translatesAutoresizingMaskIntoConstraints = false
innerView.addSubview(vLabel)
vLabel.centerXAnchor.constraint(equalTo: innerView.centerXAnchor).isActive = true
vLabel.centerYAnchor.constraint(equalTo: innerView.centerYAnchor).isActive = true
let containerView = UIView()
containerView.addSubview(innerView)
innerView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
innerView.topAnchor.constraint(equalTo: containerView.topAnchor),
innerView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
innerView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
innerView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
])
containerView.frame.size.height = 60
tableView.tableHeaderView = containerView
// desired alpha value on innerView
innerView.alpha = 0.1