swift 개발

[swift] dynamic tableview cell height, uitableview 다른크기의 셀높이 지정하기.

arcjeen 2017. 7. 5. 13:59


1.ROW


테이블뷰 안의 셀에 각각 다른 크기의 컨텐츠가 들어가서 높이를 다르게 지정해줘야 될 경우


tableview cell row height 에 UITableViewAutomaticDimension  속성을 주어 사용하면


테이블뷰가 자동으로 셀컨텐츠의 내용을 계산해서 높이를 맞춰준다.



 tableview.rowHeight = UITableViewAutomaticDimension;

 tableview.estimatedRowHeight = 130;



row height을 지정해준뒤 estimatedrowheight값을 지정해줘야되는데 이 프로퍼티는 


최초의 기본값정도라고 볼 수 있다.


저속성값대로 처음 지정되었다가 autolayout을 통해 뷰크기를 리사이징 해주는 것이다.


tableview cell 자체에 autolayout을 지정해주는 것이라고 보면된다.


위의 속성을 tableview가 선언된곳에서 지정해준뒤  아래와 같이 델리게이트 메서드를 


구현해주면된다.



    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {


return UITableViewAutomaticDimension


}


단순 텍스트를 담는 테이블뷰라면 위의 속성과 메서드만 구현해주어도 상관이없겟지만


customcell을 쓸때 주의할점은 cell의 contentView가 cell안의 ui요소 첫번째 요소의 top과


ui요소중 가장 아래에있는 요소의 bottom에 맞춰지게되는데 특정높이를 유지해야되는경우


에는 그 높이에맞는 view를 밑에 하나 깔아주고 equalheight constraint 조건을 걸어준뒤 


다른 요소들을 해당 view로 wrapping 해주면 된다.


contentview의 width의경우는 테이블뷰 크기에따라 자동으로 리사이징된다.


2.section


section header 또한 위의 같은 방식으로 dynamic하게 높이를 지정해줄 수 있지만


왜인지 custom section header를 사용할경우 estimateheight 메서드를 사용할 수 


없게 되어 있다. 이는 애플 가이드 문서에보면 


viewforheader in section 델리게이트 메서드는  heightforheader in section 메서드와 같이 선언되었을때 사용할 수 있다.


고나와있다. 그러므로 커스텀 헤더를 쓸 경우에는 전역변수로 헤더 높이를 잡아주고 


그 값을 리턴해주는수 밖에 없는 것 같다.. 


 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

      

       let sectionHeader = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.frame.width, height: 40))

        

        return sectionHeader;

    }

    

    

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

        return 40;

    }

    

    func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {

        

    }





custom section header를 사용할 경우 viewforheaderinsection이라는 메서드를통


해 지정해주면되는데 만약  tableview 선언부에서 section height에 


uitableviewautodemention 속성을 걸어주고 estimateheightforHeaderInSection 


메서드를 구현하면  viewforheaderinsection 메서드가 호출되지 않는다.



*TIP


만약 드롭 다운 형식의 테이블뷰를 사용하고 있을때 테이블뷰 크기를 동적으로 계속 


할당해 주어야 한다면

var heightOfTableView: CGFloat = 0.0

            let cells = self.visibleCells

            for cell in cells {

                heightOfTableView += cell.frame.height

            }


위의방법을통해 보이는 셀의 높이를 계산해주어 동적으로 바꾸어주는게좋다