본문 바로가기

swift/snapkit

snapkit(7)

테이블 동적높이 


기본 테이블 

이미지 | 제목 

           | 내용



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

테이블뷰의 estimatedRowHeight는 예상되는 높이(나중에 동적으로 변경되기때문에 어림잡아 세팅하면 됨) 

테이블뷰의 rowHeight는 반드시 UITableViewAutomaticDimension로 설정해야된다.



import UIKit

class TableView1Controller: UIViewController {
  var didSetupConstraints = false

  let cellName = "tableview1cell"

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

  let dummyList: [TableView1Model] = [
    TableView1Model(name: "test1", imageUrl: "https://lorempixel.com/100/101/", desc:
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry."),
    TableView1Model(name: "test2", imageUrl: "https://lorempixel.com/100/102/", desc:
    "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout."),
    TableView1Model(name: "test3", imageUrl: "https://lorempixel.com/100/103/", desc:
    "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old."),
    TableView1Model(name: "test4", imageUrl: "https://lorempixel.com/100/104/", desc:
    "There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable."),
  ]


  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() -> TableView1Controller {
    let vc = TableView1Controller()
    return vc
  }
}


extension TableView1Controller: UITableViewDelegate, UITableViewDataSource {
  public func initTableView() {
    self.tableView.dataSource = self
    self.tableView.delegate = self
    self.tableView.estimatedRowHeight = 70.0
    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.register(TableView1Cell.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: TableView1Cell = tableView.dequeueReusableCell(withIdentifier: self
      .cellName) as! TableView1Cell
    cell.bind(model:self.dummyList[indexPath.row])
    return cell
  }

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


//snapkit

extension TableView1Controller {
  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 TableView1Model{
  var name:String?
  var imageUrl:String?;
  var desc:String?

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



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


import UIKit
import SnapKit
import Kingfisher

class TableView1Cell: UITableViewCell {
  let userImage: UIImageView = {
    let imgView = UIImageView()
    imgView.layer.borderColor = UIColor.gray.cgColor
    imgView.layer.borderWidth = 1.0
    return imgView
  }()
  var userName: UILabel = {
    let label = UILabel()
    label.font = .systemFont(ofSize: 15)
    label.textColor = .red
    return label
  }()
  var userDesc: UILabel = {
    let label = UILabel()
    label.font = .systemFont(ofSize: 14)
    label.textColor = .black
    label.numberOfLines = 0
    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: TableView1Model) {
    self.userName.text = model.name
    self.userImage.kf.setImage(with:URL(string: model.imageUrl!))
    self.userDesc.text = model.desc
  }
}

extension TableView1Cell {
  func setupUI() {

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


    userImage.snp.makeConstraints({ (make) in
      make.top.left.equalTo(10)
      make.width.height.equalTo(40)
    })

    userName.snp.makeConstraints { (make) in
      make.top.equalTo(10)
      make.left.equalTo(userImage.snp.right).offset(10)
      make.right.equalTo(-10)
      make.height.equalTo(21)
    }

    userDesc.snp.makeConstraints { (make) in
      make.top.equalTo(userName.snp.bottom).offset(5)
      make.left.equalTo(userImage.snp.right).offset(10)
      make.right.equalTo(-10)
      make.bottom.equalTo(-10)
    }

  }
}


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

눈여겨 볼게 userDesc의  maxLine이 0이다 이렇게 되면 모든 컨텐츠가 라인제한 없이 나오게 된다.





결과화면







https://github.com/choiks14/SnapkitTest



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

snapkit(9)  (0) 2017.06.25
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