clamp
Clamp
clamp
글쓰기 관리
전체 방문자
오늘
어제
  • 분류 전체보기 (509)
    • IOS (85)
    • SwiftUI+TCA+Combine (9)
    • RxSwift + MVVM (56)
    • Clean Architecture (12)
    • SWIFT (56)
    • iOS - TDD (2)
    • 디자인패턴 (4)
    • CS (56)
      • 알고리즘 (29)
      • 운영체제 (15)
      • 자료구조 (2)
      • 네트워킹 (4)
      • 기타 (6)
    • 회고 (0)
    • Firebase (18)
    • SwiftUI (10)
    • iOS - UIKit (11)
    • iOS - 오픈소스 (6)
    • 코딩테스트 (166)
      • 프로그래머스 (164)
    • 정보처리기사 (14)
    • GitHub (2)
글쓰기 / 관리자

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Swift
  • Q
  • ㅅ
  • uikit

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
clamp

Clamp

iOS - UIKit

UIkit - UITableView

2022. 2. 24. 15:34

UITableView:

- 데이터를 목록형태로 보여줄 수 있는 UI컴포넌트

- 여러개의 셀을 가지고있고, 한개의 열과 여러줄의 행을 가지고 있으며, 수직으로만 스크롤이 가능하다.

- DataSource는 Data를 받아 뷰를 그려주는 역할

- Delegate는 TableView의 동작과 외관을 담당한다.

 

UITableViewDelegate를 통해 데이터를 전달받을 수 있다.

 

tableView.reloadData() //테이블뷰의 데이터를 다시 읽어옴
tableView.rowHeight = 60 // 셀의 높이 설정


// 스토리보드서 identifire를 지정한게 코드로 작성할 경우 register에서 작성
// 코드로 작성한 경우 커스텀 셀 등록 / 메타타입⤵️
 tableView.register(MyTableViewCell.self, forCellReuseIdentifier: "MemberCell")
 
 // 테이블 뷰 선 없애기
        tableView.separatorStyle = .none

Cell 커스터마이징.

Cocoa Touch Class로 생성하고, Subclass of: UITableViewCell로 설정하고, Also create XIB file은 체크한다.

이후에 생기는 XIBfile에서 커스터마이징을 하게된다.

이 후 메인 스토리 보드의 테이블 뷰의 셀을 클릭하고 속성 인스펙터의 Identifier에 이 전에 생성한 Cocoa Touch Class의 이름을 적는다.

클래스도 마찬가지로 지정해준다.

 

테이블 뷰에서 커스텀 셀을 사용하기위해 TableViewController 클래스에서 viewdidload메서드에 UITableView.register라는 함수를 써서 미리 셀을 등록해야한다. (코드로 작성할 때 필수)

	let nibName = UINib(nibName: "지정한 셀 클래스 이름", bundle: nil)
        tableView.register(nibName, forCellReuseIdentifier: "String")
        
// 코드로 작성한 경우
 tableView.register(MyTableViewCell.self, forCellReuseIdentifier: "MemberCell")
 
 
 
 class 커스텀클래스: UITableviewCell{
 
     // 스토리보드 또는 Nib으로 만들 때, 사용하게 되는 생성자 코드
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        MainimageView.contentMode = .scaleToFill
    }

forCellReuseIdentifier: 에는 위에서 지정한 Identifier를 적어준다.

 


TableViewDataSource

    // 테이블 뷰의 셀의 개수를 설정
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          ex) return 배열.count
    }

    //셀을 설정
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> 
        UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "String", for: indexPath) as? 
        "String" else { return UITableViewCell() }
        
        //아래의 셀에 들어갈 내용을 추가해준다.
        //ex)
        cell.rankLabel.text = "\(creditCardList[indexPath.row].rank)위"
        
        return cell
    }

 

let cell = tableView.dequeueReusableCell(withIdentifier: "String", for: indexPath)는 간단히 말해 표시해야할 셀이 1000개, 내 화면에 셀을 6개 표시할 수 있다면 1000개의 셀 중에 6개만 메모리에 올라간다는 뜻의 메서드이다.

withIdentifier: Identifier를 넣어주면 되고

for: IndexPath를 넣어준다.

return:  만약  Identifier에 지정한 셀을 할당하는데 실패를 했다면 일반적인 UiTableViewCell을 반환하라 라는 뜻


 

TableViewDelegate 

    // 셀의 높이를 지정해주는 메서드
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //지정할 만큼의 높이를 return해준다.
        return 80
        
        // 셀의 크기를 알아서 크기에 맞게 설정
        return UITableView.automaticDimension
    }
    
    // 셀이 선택되었을 때 실행되는 메서드
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        <#code#>
    }

 

셀을 좌, 우로 스와이프 할 경우 나타나는 액션

Delegate함수를 이용해서 구현할 수 있다.

 

1. 

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

canEditRowAt 메서드에 true를 반환해준다.

 

2.

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        //ex)
        if editingStyle == .delete{
        	//삭제 코드 구현. 
        }
    }

commit 메서드에 삭제하는 코드를 집어넣어 준다.

 

let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! MovieCell
        
let movie = moviesArray[indexPath.row]
        
cell.mainImageView.image = movie.movieImage
cell.movieNameLabel.text = movie.movieName
cell.descriptionLabel.text = movie.movieDescription
cell.selectionStyle = .gray //선택 시 스타일

 

 

저작자표시 비영리 동일조건 (새창열림)
    'iOS - UIKit' 카테고리의 다른 글
    • UIKit - UITextfield
    • IOS - Navigation Controller
    • UIKIT. 화면간 데이터 전달.
    • UIKIT. UINavigationController
    clamp
    clamp
    주니어 iOS개발자의 발악!!!!!!!

    티스토리툴바