Last active
January 21, 2020 18:46
-
-
Save kylebshr/4969de5ad2386fdbf6d640747ece5e4c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// Table | |
// | |
// Created by Kyle Bashour on 1/21/20. | |
// Copyright © 2020 Kyle Bashour. All rights reserved. | |
// | |
import UIKit | |
class ViewController: UITableViewController { | |
override func numberOfSections(in tableView: UITableView) -> Int { | |
return 10 | |
} | |
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return 1 | |
} | |
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = TableTableViewCell() | |
return cell | |
} | |
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { | |
return "Section \(section)" | |
} | |
} | |
class IntrinsicallySizedTableView: UITableView, UITableViewDataSource { | |
/// This is the trick - tells autolayout what size the table view should be | |
override var intrinsicContentSize: CGSize { | |
contentSize | |
} | |
/// And this ensures whenever the table view reloads/changes the intrinsic size is updated | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
invalidateIntrinsicContentSize() | |
} | |
init() { | |
super.init(frame: .zero, style: .plain) | |
dataSource = self | |
} | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return 10 | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = UITableViewCell() | |
cell.textLabel?.text = "Row \(indexPath.row)" | |
return cell | |
} | |
} | |
class TableTableViewCell: UITableViewCell { | |
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { | |
super.init(style: style, reuseIdentifier: reuseIdentifier) | |
let table = IntrinsicallySizedTableView() | |
table.translatesAutoresizingMaskIntoConstraints = false | |
contentView.addSubview(table) | |
NSLayoutConstraint.activate([ | |
table.topAnchor.constraint(equalTo: contentView.topAnchor), | |
table.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), | |
table.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), | |
table.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), | |
]) | |
} | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment