본문 바로가기

App/iOS

iOS 공부(2) Table View(테이블 뷰)

728x90
반응형

Table View(테이블 뷰)

  • 리스트 형식으로 보여줄때에 사용한다.
  • 사용하는 예시 ) 메세지, 전화번호 부 등에서 셀들이 아래로 나열 되게 보여질 때 사용한다.

 

1. Project 생성 후 스토리 보드에 Table View 추가

2. Add Constraints 상하좌우 모두 추가

3. ViewController 로 돌아가 UITableViewDelegate, UITableViewDataSource 추가

4. 임의의 셀을 만들 경우 , tableView 함수 중 numberOfRowsInSection에는 cell을 몇개 만들 지 리턴 할 값을 넣는다.

5. cellForRowAt에는 셀에 들어갈 내용을 넣고 리턴 한다. 

- 임의로 작성한 내용은 셀의 숫자를 넣도록 함.

6. main 스토리 보드에 control 누른 후 ViewController에 추가하고 이름을 설정하여 Connect 클릭.

7. viewDidLoad() 호출 하는 부분에 추가한 TableMain에  delegate와 dataSource 를 추가한다.

8. 실행하여 결과 확인 

 

전체 소스 

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var TableMain: UITableView!
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //임의의 셀을 정할 경우, 셀의 개수를 리턴함
        return 10
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell.init(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = "\(indexPath.row)"
        
        return cell
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        //self => 클래스 안에 function을 의미함
        TableMain.delegate = self
        TableMain.dataSource = self
    }


}

 

728x90
반응형