2017-11-23 28 views
0

버튼을 클릭 할 때 UITableView 드롭 다운을 달성하려고합니다. 처음에는 tableView이 숨겨져 있어야하고 사용자가 버튼을 누르면 드롭 다운해야합니다. 나는 UIStackView으로 이것을 달성하려고 노력했지만 성공하지는 못했다. 어쩌면 내가 잘못하고있는 것일 수도 있고 아니면 다른 접근법이있을 수도 있습니다.UITableView를 스택 뷰로 드롭 다운

let stackView = UIStackView() 
var btn: UIButton! 
var myTableView = UITableView() 

override func viewDidLoad() { 
    super.viewDidLoad() 
    myTableView.delegate = self 
    myTableView.dataSource = self 
    myTableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 1)) 
    myTableView.frame = CGRect(x: 0, y: 0, width: 300, height: 200) 
    myTableView.center = CGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2) 
    myTableView.showsVerticalScrollIndicator = false 

    btn = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50)) 
    btn.backgroundColor = UIColor.blue.withAlphaComponent(0.3) 
    btn.setTitle("DropDownMenu", for: UIControlState.normal) 
    btn.titleLabel?.textColor = .white 
    btn.titleLabel?.textAlignment = .center 
    btn.center = CGPoint(x: self.view.frame.width/2, y: myTableView.center.y - myTableView.frame.height/2 - btn.frame.height/2) 
    btn.addTarget(self, action: #selector(btnPressed), for: UIControlEvents.touchUpInside) 

    stackView.axis = UILayoutConstraintAxis.vertical 
    stackView.distribution = UIStackViewDistribution.equalSpacing 
    stackView.alignment = UIStackViewAlignment.center 
    stackView.spacing = 16.0 
    stackView.translatesAutoresizingMaskIntoConstraints = false 

    self.view.addSubview(btn) 
    stackView.addSubview(myTableView) 
    self.view.addSubview(stackView) 

} 

@objc func btnPressed() { 
    UIView.animate(withDuration: 1) { 
     self.myTableView.isHidden = !self.myTableView.isHidden 
    } 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return 4 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = UITableViewCell() 
    cell.textLabel?.text = "This is cell " + indexPath.row.description 
    cell.textLabel?.textColor = .black 
    return cell 
} 

나는 tableView가 있지만 애니메이션 사라질 수 있습니다. 이견있는 사람?

+0

'UIView.animate' 블록을 사용하지 않으셨습니까? – jjatie

+0

@jjatie 예, 동일한 동작입니다. –

+0

전 똑같은 일을했습니다. 유일한 차이점은'UIView.animate'를 호출하지 않고'stackView.translatesAutoresizingMaskIntoConstraints = false'를 설정하지 않는다는 것입니다. 그런 다음 스토리 보드 (또는 코드)에서 적절한 제한이 있는지 확인하십시오. 내 경험상,'UIStackView'는 자동 레이아웃이 필요합니다. – jjatie

답변

0

내가 끝내는 접근 방식은 UIStackView을 거치지 않았지만 tableView의 프레임을 애니메이션하는 버튼이 있습니다. 프레임은 처음에는 화면 너비와 높이 0으로 설정됩니다. 사용자가 버튼을 누르면 높이를 설정합니다.

UIView.animate(withDuration: 0.25, animations: { 
      self.menuTable.frame = CGRect(x: 0, y: (sender.center.y + sender.frame.height/2), width: self.view.frame.width, height: yourHeight) 
     })