iyOmSd/Title: Swift

[Swift] - TableView Header 및 Swipe Delete Action

냄수 2020. 5. 12. 23:57
반응형

TableView에서

Cell위에 View를 추가할 수 있는데 그거를 HeaderView라고 불러요

아래에 FooterView도 추가할 수 있어요

 

Section마다 각각 하나씩  추가할 수 있어요

 

이런 디자인이 있을 때

회색의 언더바 밑으로는 Cell이구요

위에는 HeaderView로 구현했어요

 

헤더뷰를 만들기는 간단해요!

바탕이될 뷰를 생성하고

그뷰에 각 컴포넌트들을 오토레이아웃 설정해주고

바탕뷰를 반환해주면 되구요

 

크기도 당연히 지정할 수 있어요

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        let underLine = UIView()
        underLine.backgroundColor = #colorLiteral(red: 0.4392156863, green: 0.4392156863, blue: 0.4392156863, alpha: 1)
        let profileImg = setupProfileImgView()
        let nickLabel = setupNickLabel()
        
        view.addSubview(underLine)
        view.addSubview(profileImg)
        view.addSubview(nickLabel)
        
        nickLabel.translatesAutoresizingMaskIntoConstraints = false
        profileImg.translatesAutoresizingMaskIntoConstraints = false
        underLine.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            profileImg.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
            profileImg.widthAnchor.constraint(equalToConstant: 60),
            profileImg.heightAnchor.constraint(equalToConstant: 60),
            profileImg.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            nickLabel.leadingAnchor.constraint(equalTo: profileImg.trailingAnchor, constant: 13),
            nickLabel.centerYAnchor.constraint(equalTo: profileImg.centerYAnchor),
            underLine.heightAnchor.constraint(equalToConstant: 0.5),
            underLine.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
            underLine.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
            underLine.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
        
        return view
    }
    
    func setupProfileImgView() -> UIImageView {
        let imgView = UIImageView()
        imgView.image = myImg
        imgView.contentMode = .scaleAspectFill
        return imgView
    }
    
    func setupNickLabel() -> UILabel {
        let label = UILabel()
        label.text = "김남수"
        label.font = .systemFont(ofSize: 17, weight: .bold)
        label.textColor = #colorLiteral(red: 0.1529411765, green: 0.1529411765, blue: 0.1529411765, alpha: 1)
        return label
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 88
    }

 

 

⚠️그리고 HeaderView를 만들고 스크롤을 했을 때 같이 스크롤안되고 위에 떠있는 경우에는⚠️

style을 Plain -> Grouped 으로 변경해주시면 잘 스크롤 될겁니다 :)

 

 

 

 

아래와 같은 스와이프기능 보신적 있으시죠?

 

 

스와이프로 수정하거나 삭제 하는 기능들은

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        
    }

이런 delegate 함수들로 구현해서 사용했었어요

설명을 하자면

canEditRowAt - edit모드를 사용할것인가

editingStyleForRowAt - 사용할 edit타입

commit - 타입에 따른 동작처리

 

이렇게 되지만

iOS11부터는 아래와같이 더 편하게 쓸 수 있어요

 

trailingSwipeActionsConfigurationForRowAt

trailing.. 끝에서 나올거같죠?

leading도 있어요 ㅎㅎ

    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        let deleteAction = UIContextualAction(style: .destructive, title: "잘가시츄..") { (action, view, success ) in
            self.mockData.remove(at: indexPath.row)
        }
        let config = UISwipeActionsConfiguration(actions: [deleteAction])
        config.performsFirstActionWithFullSwipe = false
        return config
    }

UISwipeActionsConfiguration - Swipe action 설정

UIContextualAction - 각 action 정의, 스와이프시 보여지는 뷰

performsFirstActionWithFullSwipe - 끝까지 스와이프 안되도록 제어기능 ( 끝까지 스와이프시 취소가아닌 작동하기 때문 )

 

 

 

반응형