セクションヘッダービューの中央にテキストラベルを追加するために、次のコードを記述しました。SwiftのtableViewSectionヘッダーにラベルとUIButtonを追加する方法は?
コードの後半は、幅が100でセクションヘッダーの右隅に揃えられたUIButton
を追加することです。
結果は、追加されたラベルのみが中央に表示されます。ヘッダーにボタンが表示されません。
実装のどこが間違っているのかを教えてください。ありがとうございました。
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
// code for adding centered title
headerView.backgroundColor = UIColor.gray
let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width:
tableView.bounds.size.width, height: 28))
headerLabel.textColor = UIColor.black
headerLabel.text = titlesList[section]
headerLabel.textAlignment = .center
headerView.addSubview(headerLabel)
// code for adding button to right corner of section header
let showHideButton: UIButton = UIButton(frame: CGRect(x:headerView.frame.size.width - 100, y:0, width:100, height:28))
showHideButton.setTitle("Show Closed", for: .normal)
showHideButton.backgroundColor = UIColor.blue
showHideButton.addTarget(self, action: #selector(btnShowHideTapped), for: .touchUpInside)
headerView.addSubview(showHideButton)
return headerView
}