apple/iOS, UIKit, Documentation

iOS SnapKit 공식문서로 공부하기 5탄 (UITableView 코드로 구성하기 1편)

lgvv 2021. 8. 19. 12:23

iOS SnapKit 공식문서로 공부하기 5탄 (UITableView 코드로 구성하기 1편)

 

SnapKit을 활용하고 실제 자주 사용하는 UITableView를 이용해보자

 

 

코드로 테이블뷰를 구성

  • ViewContoller에서 tableView를 선언한다.
  • tableView에 register를 통해서 tableViewCell의 id를 입력한다.
  • tableview의 delegate 및 dataSource를 채택해 구현한다
  • addSubView를 사용하여 tableView를 넣는다.

 

코드로 테이블뷰 셀을 구성

  • id값을 선언한다
  • init 함수를 구현한다.
    • override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) 
    • required init?(coder: NSCoder)
  • view가 아는 contentView에 필요한 UI 요소를 addSubview 한다.

 

코드 리뷰

//
//  ViewController.swift
//  SnapKit_Practice
//
//  Created by Lee Geon Woo on 2021/08/19.
//

import UIKit

final class ViewController03Cell : UITableViewCell {
    
    static let identifier = "ViewController03Cell"
    
    let img : UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "icon")
        imgView.translatesAutoresizingMaskIntoConstraints = false
        return imgView
    }()
    
    let label : UILabel = {
        let label = UILabel()
        label.text = "상어상어"
        label.textColor = UIColor.gray
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        addContentView()
        autoLayout()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func addContentView() {
        contentView.addSubview(img)
        contentView.addSubview(label)
    }
    
    private func autoLayout() {
        let margin : CGFloat = 10
        NSLayoutConstraint.activate([
            img.topAnchor.constraint(equalTo: self.topAnchor),
            img.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            img.widthAnchor.constraint(equalToConstant: 100),
            img.heightAnchor.constraint(equalToConstant: 100),
            
            
            label.topAnchor.constraint(equalTo: self.topAnchor),
            label.leadingAnchor.constraint(equalTo: img.trailingAnchor, constant: margin),
            label.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            
                    ])
    }
}

class ViewController03 : UIViewController {
    
    private let tableView : UITableView = { // 테이블 뷰 생성
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.register(ViewController03Cell.self, forCellReuseIdentifier: ViewController03Cell.identifier)
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configure()
        addSubView()
        autoLayout()
    }
    
}

extension ViewController03 {
    
    private func configure() {
        tableView.dataSource = self
        tableView.rowHeight = 100
        tableView.delegate = self
    }
    
    private func addSubView() {
        view.addSubview(tableView)
    }
    
    private func autoLayout() {
        let guide = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: guide.topAnchor),
            tableView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: guide.bottomAnchor)
        ])
    }
}

extension ViewController03 : UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: ViewController03Cell.identifier, for: indexPath) as! ViewController03Cell
        cell.img.image = UIImage(systemName: "ticket")
        cell.label.text = "\(indexPath.row)"
        return cell
    }
}

extension ViewController03 : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("select \(indexPath.row)")
    }
}

tableView 결과

 

 

 

더 복잡한 것들도 진행해보자