2017-10-01 16 views
0

セクションヘッダービューの中央にテキストラベルを追加するために、次のコードを記述しました。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 
} 

答えて

1

あなたの問題は、この行です:

let headerView = UIView() 

あなたが任意のフレームを指定していませんしたがって、下の行は、showHideButtonフレームの認識サイズにはなりません。

let showHideButton: UIButton = UIButton(frame: CGRect(x:headerView.frame.size.width - 100, y:0, width:100, height:28)) 

あなたが宣言するときに代わりにこの行を使用して、あなたのheaderViewenter image description here

:これは以下のように表示されます

let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 100)) 

1

let showHideButton: UIButton = UIButton(frame: CGRect(x:headerView.frame.size.width - 100, y:0, width:100, height:28)

あなたのボタンのX位置がheaderViewマイナス100の大きさである。しかし、あなたのheaderViewは、幅がこのようにあなたのボタンがに配置されている0ですだ意味なしフレーム(let headerView = UIView())を、持っていませんX -100。

私はあなたがタイプミスをしたと仮定して、表の幅に基づいて、それを配置するためのもの:

let showHideButton: UIButton = UIButton(frame: CGRect(x:tableView.bounds.size.width - 100, y:0, width:100, height:28)

関連する問題