<--! [IOS] 테이블뷰 만들기 (4) : 커스텀 테이블 만들기 -->

[IOS] 테이블뷰 만들기 (4) : 커스텀 테이블 만들기

필그램

·

2017. 8. 31. 05:18

커스텀 테이블 만들기 

File > New에서 파일을 추가하도 CustomCell.swift라고 이름을 정한다. 

Subclass는 UITableViewCell을 선택한다.



스토리뷰에서 셀을 선택하고, 오른쪽 inspector의 Class에서 새로 만들어준 파일을 선택한다.








그리고 Cell 안에 label 과 Switch를 넣는다.

이것을 새로만든 파일안에 label이라고 이름지어 연결한다.










[수정코드]

ViewController.swift에서


        // 14. (커스텀 테이블 만들기) 코드 대신 아래로 수정

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

        

        cell.label?.text = data[indexPath.section][indexPath.row]  // 7. 수정




[전체 코드]


import UIKit


class ViewController: UIViewController, UITableViewDataSource {

    //0. UITableViewDataSource 입력

    

    //3. 어레이 입력- 5. 중복 어레이 입력

    let data:[[String]] = [["Item1", "Item2", "Item3"], ["ItemA", "ItemB", "ItemC"]]

    

    //11. 소제목 내용 입력

    let sub:[[String]] = [["sub1", "sub2", "sub3"], ["subA", "subB", "subC"]]

    

    //10. 헤더 제목 입력

    let headers:[String] = ["Numbered", "Lettered"]


    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }


    // 1. numberOfRowsInSection - 어레이를 카운팅

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return data[section].count

    }

    

    //6. 섹션이 몇개인지 확인하여 추가

    func numberOfSections(in tableView: UITableView) -> Int {

        return data.count

    }

    

    //2.cellForRowAt -

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

//        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        //4.dequeueReusableCell 입력후, 스토리보드에서 "cell" 입력

        

        // 14. (커스텀 테이블 만들기) 코드 대신 아래로 수정

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

        

        cell.label?.text = data[indexPath.section][indexPath.row]  // 7. 수정

        

        //12. 소제목 리스팅

//        cell.detailTextLabel?.text = sub[indexPath.section][indexPath.row]

        

        //13. 스토리보드에서 star 선택하는 대신 코드로 넣을수도 있다.

//        cell.imageView?.image = UIImage(named: "star")

        

        return cell

        //8. 스토리보드에서 Table View style Plain에서 Grouped 변경 -> 리스트가 그룹으로 나뉘어짐.

    }

    

    //9. 섹션의 제목 입력하기

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        return headers[section]

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

}






반응형