<--! [IOS] 테이블뷰 만들기 (3) : 소제목 넣고, 이미지 추가 -->

[IOS] 테이블뷰 만들기 (3) : 소제목 넣고, 이미지 추가

필그램

·

2017. 8. 31. 04:48

이번 단계는  테이블뷰 만들들기(2)에 이어, 각소제목 넣고, 이미지 추가하는 것이다.



각 카테고리 아래에 조그만 제목을 추가하고, 왼쪽의 별 이미지를 보이기 위한 작업이다.

먼저 이미지를 추가한다.




Asset~  항목에 이미지를 끌어다 넣고, 오른쪽 속성 Attribute의 Name에 'star'라고 넣는다.



다음으로 스토리보드에서 셀 -> 속성을 선택하고 Style을 Subtitle로 한다음. 이미지를 아까 정해준 star로 넣는다. 뒷 부분은 코드로 넣는것으로 대신할 수 있다.(코드를 제외해도됨)


그리고, 소제목을 어레이로 배치한다. 

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


소스코드는 아래와 같다 


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" 입력

        cell.textLabel?.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.

    }

}

반응형