2017-10-01 2 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

당신의 문제가이 행입니다 :

은 당신이 오타를 만들고, 테이블의 폭에 따라 그 위치를 의미한다고 가정 크기와 따라서 아래 행은 showHideButton 프레임의 인식 크기가되지 않습니다.

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

당신이 선언 할 때 대신 행을 사용하여 headerView : enter 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 headerView = UIView() 

당신은 어떤 프레임을 지정하지 않은 :

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

관련 문제