ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [ios - Swift] UITableView CustomCell 만들기 (UITableView 1/2)
    ios 2020. 11. 17. 22:30

     

     

     

    1. 스토리보드 화면 구성

     

    우선 UITableView 내 UITableViewCell을 추가하여 아래 이미지와 같은 구조로 제작 후

     

    TableView Row에서 보여주고 싶은 오브젝트를 추가하면 됩니다.

     

     

     

     

     

    저는 사진, 이름, 상태 메시지를 나타낼 수 있는 Row를 만들기 위해 UIImageview, Lable을 추가했습니다.

     

    이때 Contrains를 잘 맞춰 주셔야 Cell 내부에 있는 오브젝트가 Row안으로 숨지 않습니다.

     

     

     

     

    마지막으로 TableViewCell을 선택 후 Attuributes inspector -> identifier을 확인하면 Reuse identifier라고 적혀있는 것을 확인할 수 있습니다.

     

    Reuse identifier은 Tableview에서 Cell을 사용하려 할 때 이전 Cell을 재사용하기 위해 부여하는 식별자라고 생각하면 될 것 같습니다. 

     

    이  Reuse identifier에 'FriendTableViewCell'라고 작성해 줍니다.

     

     

     

     

    2. Custom Class 생성

     

     

    프로젝트 내비게이터에서 New File을 선택 후 아래와 같이 파일을 생성해 줍니다.

     

    Subclass는 UITableViewCell을 선택해 주세요.

     

     

     

     

     

    이제 메인 스토리보드에서 UITableViewCell의  Show identity inspector -> Custom Class 의 Class를 연결해 준 후 

     

    TableViewCell 내 오브젝트를 아울렛으로 연결해 줍니다.

     

     

     

     

    마지막으로 뷰 컨트롤러에서 아래와 같이 작성해 주시면 됩니다.

     

     

    import UIKit
    
    class ViewController: UIViewController {
        
        @IBOutlet weak var mTableView: UITableView!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            mTableView.delegate = self
            mTableView.dataSource = self
        }
        
    }
    
    
    extension ViewController: UITableViewDelegate, UITableViewDataSource {
        // 보여지는 Row 수
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 10
        }
        
        // indexPath.row에 맞는 Cell을 구현 
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "FriendTableViewCell") as! FriendTableViewCell
            
            cell.imageView?.image = UIImage(systemName: "pencil.circle")
            cell.mName.text = "이름 \(indexPath.row)"
            cell.mStateMsg.text = "상태 메시지 \(indexPath.row)"
            
            return cell
        }
    }

     

     

    결과는 아래와 같습니다.

     

     

    댓글

Designed by Tistory.