반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

[Swift] Table View 만들기

2015. 10. 15. 05:55 | Posted by 솔웅


반응형

원문



테이블 뷰 만들기

1. 새 프로젝트 만들기
Single Page Application 을 선택하고 프로그래밍 언어로 Swift를 선택해서 Project를 만든다.

2. 테이블 뷰 프로퍼티 추가하기
Viewcontroller.swift 에 tableview instance 변수를 추가한다. 

    @IBOutlet
    var tableView: UITableView!


@IBOutlet 속성은 Interface Builder 에 tableView property 를 보이도록 만든다.

3. TableView Delegate 와 DataSource 프로토콜 confirm 하기
UITableViewDelegate 와 UITableViewDataSource  프로토콜을 UIViewController 클래스 정의 바로 다음에 넣는다. (, 로 구분)


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    ...

}



그리고 나서 tableView(_:numberOfRowsInSection:), tableView(_:cellForRowAtIndexPath:) ,tableView(_:didSelectRowAtIndexPath:) 메소드들을 ViewController 클래스 안에 implement 한다. 일단 이 메소드들은 빈 상태로 둔다.


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    ...

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return UITableViewCell()
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    }

}



4. view controller 에 table view를 추가한다.
Component Library에서 Table View를 찾은 후 그 뷰를 끌어서 해당 view에 놓는다.

5. Interface Builder Outlets 와 연결한다.
Referencing Outlet을 dataSource와 Delegate outlet에연결한다.




6. cell class 를 Register 한다.
viewDidLoad 메소드에서 registerClass(_:forCellReuseIdentifier:)를 호출한다.
팁:이 클래스를 얻으려면 self 를 타입하고 tableView를 넣은 다음에 얻으면 된다.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    ...

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    ...

}



7. Display 할 데이터를 만든다.

스트링 배열로 items 라고 하는 property를 추가한다. 그리고 몇개의 값들을 넣는다.


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var items: [String] = ["We", "Heart", "Swift"]

    ...

}



8. row 갯수를 세팅한다.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    ...

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }

    ...

}



9. cell을 생성한다.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    ...

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

        cell.textLabel?.text = self.items[indexPath.row]

        return cell
    }

    ...

}



10. cell selection을 처리한다.
Another new thing in Swift is String Interpolation that let’s you add arbitrary code inside a string.


Some examples:

var one = "\(1)" // "1"
var two = "\(1 + 1)" // "2"

var name = "Andrei Puni"
println("my name is \(name) and I heart Swift") // will print "my name is Andrei Puni and I heart Swift"
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    ...

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("You selected cell #\(indexPath.row)!")
    }

    ...

}

By now your ViewController class should look like this:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet
    var tableView: UITableView
    var items: [String] = ["We", "Heart", "Swift"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

        cell.textLabel?.text = self.items[indexPath.row]

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("You selected cell #\(indexPath.row)!")
    }
}



UITableViewDelegate

 UITableView 객체를 delegate 하기 위해서는 반드시 UITableViewDelegate 프로토콜을 adopt 해야 한다. 이 프로토콜의 optional 메소드들은 selection들을 관리하고 section heading과 footer들을 configure 하고 각 셀들을 delete하거나 reorder 하는 등의 처리를 하기 위한 delegate 를 가능하게 한다.
 

UITableViewDelegate 프로토콜의 만은 메소드들은 NSIndexPath 객체를 파라미터로 취하고 값을 return 한다. UIKit 는 rowsection index 값을 얻는 것을 가능하도록 하는 NSIndexPath 에 대한 카테고리를 정의한다. 또한 주어진 row, section index로부터 index path를 만드는 것도 정의한다. (indexPathForRow:inSection: method). row들은 section 안에 위치해 있기 때문에 row index 값을 정의하기 이전에 section index 값을 먼저 처리해야 한다.

Configuring Rows for the Table View




UITableViewDataSource

 UITableViewDataSource 프로토콜은 UITableView 객체에 대한 어플리케이션의 데이터 모델을 중개하는 객체에 의해 adopt 된다. 데이터 소스는 테이블 뷰를 구성하고 변경하는데 필요한 정보들을 가지고 있는 테이블뷰 객체를 제공한다.

데이터 모델의 대리인으로서 데이터 소스는 테이블 뷰에 대한 최소한의 정보를 전달한다. 테이블 뷰 객체의 delegate (UITableViewDelegate protocol 을 adopt 한 object)가 그 정보를 제공한다.


이 프로토콜의 required 메소드들은 테이블 뷰에 표시될 cell 들을 제공하고 UITableView 객체에게 section 갯수와 각 section별 row들의 갯수를 알려준다. 데이터 소스는 optional 메소드들을 implement 할 수 있는데 테이블 뷰의 여러가지 부분들을 configure 하거나 row들을 insert, delete, reorder 하는데 사용할 수 있다.

Note

테이블 뷰의 swipe-to-delete 기능을 사용하려면 tableView:commitEditingStyle:forRowAtIndexPath: 메소드를 implement 해야 한다.

많은 메소드들이 NSIndexPath 객체를 파라미터로 받는다. UITableView는 rowsection index 에 대한 값을 얻도록 하는 NSIndexPath 에 대한 카테고리를 정의한다. 그리고 주어진 row, section index로부터 index path 를 구성한다.(indexPathForRow:inSection: class method) 각 index path의 첫번째 index 는 section을 나타내고 그 다음 값은 row 를 나타낸다.

Configuring a Table View


반응형