본문 바로가기

swift/snapkit

snapkit(6)

이번에는 가장 많이 사용되는 tableview를 사용해보자


사실 tableview를 만들다기 보단 tableviewcell를 동적으로 만드는게 주 목적이다.



기본 테이블 

이미지 | 제목 | disclosureindicator



1.테이블 뷰를 생성한다.


import UIKit

class TableView2Controller: UIViewController {

  var didSetupConstraints = false

  let cellName = "tableview2cell"

  let tableView: UITableView = {
    let tableView = UITableView()
    return tableView
  }()

  let dummyList: [TableView2Model] = [
    TableView2Model(name: "test1test1test1test1test1test1test1test1test1test1test1test1test1test1", imageUrl: "https://lorempixel.com/100/101/"),
    TableView2Model(name: "test2test1test1test1test1test1test1test1test1test1test1test1test1test1", imageUrl: "https://lorempixel.com/100/102/"),
    TableView2Model(name: "test3test1test1test1test1test1test1test1test1test1test1test1test1test1", imageUrl: "https://lorempixel.com/100/103/"),
    TableView2Model(name: "test4test1test1test1test1test1test1test1test1test1test1test1test1test1", imageUrl: "https://lorempixel.com/100/104/"),
  ]


  override func viewDidLoad() {
    super.viewDidLoad()

    self.initUI()

    self.initTableView()

    // Do any additional setup after loading the view.
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }

  static func instance() -> TableView2Controller {
    let vc = TableView2Controller()
    return vc
  }

}


extension TableView2Controller: UITableViewDelegate, UITableViewDataSource {
  public func initTableView() {
    self.tableView.dataSource = self
    self.tableView.delegate = self
    self.tableView.rowHeight = 80.0
    self.tableView.register(TableView2Cell.self, forCellReuseIdentifier: self.cellName)
  }

  public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)
      -> Int {

    return self.dummyList.count
  }

  public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
      -> UITableViewCell {
    let cell: TableView2Cell = tableView.dequeueReusableCell(withIdentifier: self
      .cellName) as! TableView2Cell
    cell.bind(model: self.dummyList[indexPath.row])
    return cell
  }

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
  }
}


//snapkit

extension TableView2Controller {
  func initUI() {
    self.view.addSubview(self.tableView)
    view.setNeedsUpdateConstraints()
  }

  override func updateViewConstraints() {
    if (!didSetupConstraints) {
      tableView.snp.makeConstraints { make in
        make.edges.equalToSuperview()
      }
      didSetupConstraints = true
    }

    super.updateViewConstraints()
  }
}



2.모델은 단순하게 생성한다. 


import Foundation

struct TableView2Model{
  var name:String?
  var imageUrl:String?;

  init(name:String,imageUrl:String) {
    self.name = name
    self.imageUrl = imageUrl
  }
}



3.가장 중요한 UITableviewCell을 생성한다.

이미지url을 로드하기 위해서 KingFisher를 사용한다.


//
import UIKit
import SnapKit
import Kingfisher

class TableView2Cell: UITableViewCell {
  let userImage: UIImageView = {
    let imgView = UIImageView()
    return imgView
  }()
  var userName: UILabel = {
    let label = UILabel()
    label.font = .systemFont(ofSize: 15)
    label.textColor = .red
    return label
  }()



  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setupUI()
  }

  override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    setupUI()
  }

  func bind(model: TableView2Model) {
    self.userName.text = model.name
    self.userImage.kf.setImage(with:URL(string: model.imageUrl!))
  }
}

extension TableView2Cell {
  func setupUI() {
    self.accessoryType = .disclosureIndicator

    self.addSubview(self.userImage)
    self.addSubview(self.userName)

    userImage.snp.makeConstraints({ (make) in
      make.left.equalTo(contentView.snp.left).offset(10)
      make.top.equalTo(10)
      make.bottom.equalTo(-10)
      make.width.equalTo(userImage.snp.height)
    })

    userName.snp.makeConstraints { (make) in
      make.centerY.equalToSuperview()
      make.left.equalTo(userImage.snp.right).offset(10)
      make.right.equalTo(contentView.snp.right)
      make.height.equalTo(21)
    }

  }
}


setupUI 에서 엘리먼트의 위치와 크기를 잡아둔다.

중요한점 disclosureIndicator를  사용하면 tableviewcell의 contentview가 disclosureIndicator 만큼 자동적으로 레이아웃을 만들어준다. 

그래서 userName의 right는 contentview의 right와 동일하게 맞춰준다.


userImage의 width를 height와 동일하게 줬다. 이렇게 되면 tableview에서 높이 값을 변경할때 마다 이미지는 항상 정사작형으로 나오게 된다. 




결과화면






https://github.com/choiks14/SnapkitTest



'swift > snapkit' 카테고리의 다른 글

snapkit(8)  (0) 2017.06.25
snapkit(7)  (0) 2017.06.25
snapkit(6)  (0) 2017.06.25
snapkit(5)  (0) 2017.06.18
snapkit(4)  (0) 2017.06.18
snapkit(3)  (0) 2017.06.18