<--! [IOS] 테이블뷰 만들기 (5) : Deligate -->

[IOS] 테이블뷰 만들기 (5) : Deligate

필그램

·

2017. 8. 31. 05:34

[결과화면]




델리게잇을 하기위해 스토리보드에서 아래처럼 연결한다.




그리고 ViewController에 클래스 첫줄에  UITableViewDelegate을 추가한다.




아래쯤에 didSelectRowAt 의 펑션을 추가하여, 리스트 클릭시 시스템에 클릭한것이 보이도록한다.








[전체 소스]


import UIKit


class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    //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]

    }

    

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("\(data[indexPath.section][indexPath.row])")

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

}




반응형