Notice
Recent Posts
Recent Comments
«   2024/03   »
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
31
Archives
Today
Total
관리 메뉴

코딩하는 빵

[IOS/Swift] Custom TableView Cell 만들기 본문

코딩하는 빵/iOS

[IOS/Swift] Custom TableView Cell 만들기

빵그레 2016. 8. 15. 21:31

UITableView의 Cell을 커스텀화 해보자!


본 포스팅은  MacOS 10.11.5, Xcode Version 7.3.1 (7D1014), Swift 2 기준으로 작성되었습니다.


1. StoryBoard 에서 TableView와 Cell 만들기


스토리보드에 TableView와 그 안에 Cell을 올리고, Cell 내부의 Content View에 커스텀할 구성요소를 추가합니다.

예제에서는 imageView와 label을 추가하였습니다.


Table View와 Table View Cell 둘 다 추가해줘야한다.


Content View에 imageView와 label 추가


2. Custom Cell Class 만들기


커스텀화한 Cell과 컨트롤러를 연결해 줄 UITableViewCell 클래스를 만들어봅시다.


Cell의 Custom Class로 새로 만든 클래스(UITableViewCell)를 등록해주고,

만든 클래스에 커스텀화 구성요소(imageView, label)의 outlet을 만들어주면 됩니다.


// swift 파일로 클래스 생성
import UIKit

class FirstCustomCell: UITableViewCell {

}


위에서 만든 클래스를 등록한다.


// imageView와 label의 outlet 추가
import UIKit

class FirstCustomCell: UITableViewCell {
    
    @IBOutlet weak var tvImageView: UIImageView!
    @IBOutlet weak var tvLabel: UILabel!
    
}


3. Cell Identifier 등록하고 컨트롤러에서 부르기


Cell의 Identifier를 등록하고 (클래스와 같은 이름으로 하는 것이 편합니다.)

컨트롤러에서  tableview에 세팅작업을 해줍시다.


등록한 Identifier는 기억하고 있자.


// label에 들어갈 string과 assets에 저장된 이미지 이름 배열
    let menus = ["swift","tableview","example"]
    let images = ["dog1","dog2","dog3"]


tableview 세팅작업의 경우 UITableViewDataSource, UITableViewDelegate 구현 그리고 등록이 필요합니다.

구현은 클래스 밖에 extension 키워드를 이용했고 delegate는 비워두었습니다.


// tableview의 datasource와 delegate 등록
extension TVinStoryboardController: UITableViewDataSource{

// table row 갯수 (menu 배열의 갯수만큼)
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return menus.count
    }
  
// 각 row 마다 데이터 세팅.
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 첫 번째 인자로 등록한 identifier, cell은 as 키워드로 앞서 만든 custom cell class화 해준다.
        let cell = tableview.dequeueReusableCellWithIdentifier("FirstCustomCell", forIndexPath: indexPath) as! FirstCustomCell
        
        // 위 작업을 마치면 커스텀 클래스의 outlet을 사용할 수 있다.
        cell.tvLabel.text = menus[indexPath.row]
        cell.tvImageView.image = UIImage(named: images[indexPath.row])
        
        return cell
    }
}

extension TVinStoryboardController: UITableViewDelegate{
    
}
// tableview의 datasource와 delegate 등록

    @IBOutlet weak var tableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        tableview.dataSource = self
        tableview.delegate = self
    }


실행결과



깃허브에서 전체코드 확인하기: https://github.com/yucaroll/swiftCustomTableViewExample


Comments