[Swift/iOS] TableView - Custom Cell

Programming/IOS 2021. 8. 24. 15:29 Posted by 생각하는로뎅
반응형
[Swift/iOS] TableView - simple 게시글 계속

 

 

1. Custom Cell에 사용할 View Controller Class를 만든다.

 

Type1.swift

//
//  Type1.swift
//  TableView
//
//  Created by sjlim on 2021/08/24.
//

import UIKit

class Type1 : UITableViewCell {

}

 

 

 

2.  Main.storyboard에 가서, Table View Cell 을 추가한다.

 

 

Table View Cell 추가된 모습

 

 

 

3. 추가한 Table View Cell에 Class를 지정한다. ( 1번에서 생성한 Type1 Class)

 

 

 

 

4.  Table View Cell에 label을 추가한다.

 

 

 

 

5. label을 Table View Cell 최대 크기로 늘리신 후, Add New Constraints 를 추가한다.

 

 

 

 

6. Table View Cell 의 id 를 type1 으로 지정한다.

 

 

 

 

7. Type1.swift를 오른쪽 클릭 후 새창으로 띄워준다.

 

 

 

 

8. 아래 스크린샷처럼 화면을 분활 한 뒤, label을 Ctl 누른채로 소스 쪽으로 드래그 앤 드롭 한다.

 

 

 

 

9. Name은 labelText 를 입력 후, Connect 버튼을 누른다.

 

 

 

 

10. ViewController.swift 를 아래와 같이 수정한다.

 

//
//  ViewController.swift
//  TableView
//
//  Created by sungjin on 2021/08/24.
//

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var tableViewMain: UITableView!
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        // cell의 개수
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 리턴 값이 부모 UITableViewCell 이므로, Type1 class로 cast 해준다.
        let cell = tableViewMain.dequeueReusableCell(withIdentifier: "type1", for: indexPath) as! Type1
        
        // labelText의 Text를 수정한다.
        cell.labelText.text = "\(indexPath.row)"
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("\(indexPath.row)")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableViewMain.delegate = self
        tableViewMain.dataSource = self
        
    }
    
    


}

 

 

 

 

11. 결과물

 

 

반응형