iOS 응용 (swift)
[iOS - swift] table view에서 특정 separator 삭제 방법 (header의 하단, 마지막 셀의 하단)
jake-kim
2020. 11. 12. 01:21
방법: CALayer를 가지고 테이블 뷰 색깔로 그려주게 되면, separator가 가려지게끔 하는 원리
- CALayer를 이용하여 UIView의 하단에 줄을 긋는 함수 정의
public extension UIView {
func addBottomBorderWithColor(color: UIColor) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height, width: self.frame.size.width, height: 1)
self.layer.addSublayer(border)
}
func addAboveTheBottomBorderWithColor(color: UIColor) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1)
self.layer.addSublayer(border)
}
}
- HeaderView에서 separator 가리는 예제
// UITableViewDelegate, UITableViewDataSource를 구현하는 곳
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if dataSource[section].type == . {
let headerView = tableView.dequeHeaderFooter(MyHeaderView.self)
headerView.addBottomBorderWithColor(color: .white) // table view색깔이 white인 경우, separator를 흰색으로 덮는 로직
return headerView
}
return nil
- 마지막 Cell의 separator 가리는 예제
- 1) 해당 cell이 마지막 cell인지 체크하는 함수추가
public extension UITableView {
func isLast(for indexPath: IndexPath) -> Bool {
let indexOfLastSection = numberOfSections > 0 ? numberOfSections - 1 : 0
let indexOfLastRowInLastSection = numberOfRows(inSection: indexOfLastSection) - 1
return indexPath.section == indexOfLastSection && indexPath.row == indexOfLastRowInLastSection
}
}
- 2) 마지막 cell에 bottom separator 가리기
func placeCell(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, place: Place, isFromRecentPlace: Bool = false) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! MyCell
if tableView.isLast(for: indexPath) {
DispatchQueue.main.async {
cell.addAboveTheBottomBorderWithColor(color: .common_c42_white)
}
}
return cell
}