티스토리 뷰

Swift + iOS/iOS

[ios] Custom Table VIew

군옥수수수 2017. 10. 17. 19:58

Custom Table View


이전까지는 기본적으로 주어지는 틀의 Table View를 만들어보았다면 이번 포스팅에서는 Cell을 직접 디자인해보는 Custom Table View를 만들어보는 시간을 갖도록 하겠습니다.


이전 포스팅을 바탕으로 작성된 글이기 때문에 처음 접하시는 분들은 아래의 글들을 먼저 읽어보시기 바랍니다.


그럼 본격적으로 시작해보도록 하겠습니다.


1) Basic Table View와의 차이점

  1. Cell Design
  2. UITableViewCell.class

먼저 Table View안에 들어가는 Cell의 디자인이 기본적으로 주어지는 것과는 다릅니다. 그렇기 때문에 이러한 커스터마이징 된 Cell의 요소들에 접근하기 위해서는 UITableViewCell을 상속받은 클래스 파일을 필요로 합니다.


화면에 뿌려줄 데이터를 세팅하는 코드는 다음과 같이 수정하였습니다.

// ViewController.swift
var dataList = [[String:String]]()

var city = ["Seoul", "New York", "Tokyo", "Barcelona", "Danang", "London", "Dallas", "Atlanta", "Moscow", "Berlin", "Paris", "Dubai", "Busan"]
var weather = ["구름 많음", "번개", "눈", "비", "맑음"]
var imgs = ["clouds.png", "lightning.png", "snowflake.png", "rain.png", "sun.png"]

override func viewDidLoad() {
    super.viewDidLoad()
    for index in 0...city.count - 1 {
        dataList.append(["city":city[index], "weather":weather[index % weather.count], "img":imgs[index % imgs.count]])
    }
}

2) Cell Design

저는 이번 포스팅에서는 Cell의 디자인을 다음과 같이 사용할 것입니다.



날씨를 나타내는 아이콘을 담을 image view와 라벨을 의미하는 두 Label과 직접 데이터를 뿌려줄 두 Label을 사용하였습니다. 저는 우측 메뉴의 Attributes Inspector에서 identifiercustomcell이라 지정하였습니다.


3) UITableViewCell.class

현재 만들어진 Cell은 기본 Cell이 아닌 우리가 직접 만든 Cell입니다. 그렇기 때문에 안의 요소들을 코드로 접근하기 위해서는 UITableViewCell.class를 상속받은 파일을 하나 만들어야 합니다.


  1. Command + N를 통해 새로운 Cocoa Touch Class파일을 선택합니다.



  2. Subclass of에서 UITableViewCell을 선택하여 해당 클래스를 상속받는 클래스 파일을 만듭니다. 저는 CustomCell이라는 이름으로 해당 클래스 파일을 생성했습니다.



  3. 이제 만든 클래스 파일과 직접 디자인한 Cell을 연결을 해주어야 합니다. identifier로 지정한 customcell을 선택하여 우측 Identity Inspector 메뉴에서 해당 Cell의 클래스를 우리가 생성한 CustomCell로 지정해줍니다. 그렇다면 연결은 끝난 것입니다.



  4. 이제는 우리가 동적으로 바꿔주어야할 Cell의 image view와 두 LabelCustomCell.class에 연결시켜줍니다.




4) More

기본적인 설정은 여기까지입니다. 이제는 직접 코드를 작성해주어야 합니다.

이전의 Basic Table View 코드와 다른 점은 tableView(_: cellForRowAt) 메소드안의 코드입니다.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "customcell", for: indexPath) as! CustomCell
        
    var currentCellWeather = dataList[indexPath.row]
    cell.areaLabel.text = currentCellWeather["city"]
    cell.weatherLabel.text = currentCellWeather["weather"]
    cell.weatherImgView.image = UIImage(named: currentCellWeather["img"]!)
    return cell
 }

우리가 커스터마이징한 Cell을 사용하기 위해서는 tableView.dequeueReusableCell메소드로 반환되는 Cell을 우리가 만들어놓은 CustomCell로 캐스팅해야합니다.


데이터를 뿌려주는 부분은 우리가 연결해놓은 요소에 데이터를 뿌려주는 코드입니다.

그리고 UITableViewDataSourceUITableViewDelegate 프로토콜을 준수한다고 명시하고 TableViewViewController와 연결을 하고 datasourcedelegate를 설정하셔야 합니다.

@IBOutlet weak var customCellTableView: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    for index in 0...city.count - 1 {
        dataList.append(["city":city[index], "weather":weather[index % weather.count], "img":imgs[index % imgs.count]])
    }
    customCellTableView.delegate = self
    customCellTableView.dataSource = self
}

5) 마무리

결과물은 다음과 같습니다.


이렇게 Custom Table View를 만들어보았습니다. 기본적으로 Basic Table View를 만드시는데 어려움이 없으시다면 이번 포스팅은 어렵지 않으실 것입니다. 다음에는 더 좋은 포스팅으로 찾아뵙도록 하겠습니다. 감사합니다.


Source : https://github.com/ehdrjsdlzzzz/tistory-ios/tree/master/tistory_custom_tableview_posting_example


날씨 아이콘 출처



'Swift + iOS > iOS' 카테고리의 다른 글

[ios] Switching View and Passing Data(1) - Code  (0) 2017.11.01
[ios] Switching View and Passing Data(1) - UI  (0) 2017.11.01
[ios] UIViewController Lifecycle  (0) 2017.10.25
[ios] Basic TableView - Code  (0) 2017.10.05
[ios] Basic TableView - UI  (0) 2017.10.05
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함