Skip to content

Instantly share code, notes, and snippets.

@monkeywithacupcake
Created March 10, 2018 11:42
Show Gist options
  • Save monkeywithacupcake/99c163a95cc47098bd1c6d9ff5ed7a63 to your computer and use it in GitHub Desktop.
Save monkeywithacupcake/99c163a95cc47098bd1c6d9ff5ed7a63 to your computer and use it in GitHub Desktop.
Make a custom table view
import UIKit
class ButtonView: UIView {
let button = UIButton()
func updateText(_ text:String?) {
guard let text = text else { return }
button.setTitle(text, for: .normal)
}
override init(frame: CGRect){
super.init(frame: frame)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Click Me", for: .normal)
// set default colors here
button.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
self.addSubview(button)
}
override func layoutSubviews() {
super.layoutSubviews()
button.frame = bounds
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} // end ButtonView
import UIKit
class ThingCell: UITableViewCell {
var cellImage: UIImageView()
var cellButton1: ButtonView()
var cellButton2: ButtonView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupStack()
}
func setupImage() {
//imageView.image = #imageLiteral(resourceName: "pinlogo") // add an image
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
}
func setupButtons() {
cellButton1.updateText("press")
// cellButton2. updateText("now")
}
func setupStack() {
setupImage()
setupButtons()
let stackView = UIStackView(arrangedSubviews: [cellImage, cellButton1, cellButton2])
stackView.axis = .horizontal
stackView.distribution = .fill
stackView.alignment = .fill
stackView.spacing = 5
stackView.translatesAutoresizingMaskIntoConstraints = false
// add some component constraints
//let imageH = cellImage.heightAnchor.constraint(equalToConstant: 80)
//stackView.addConstraint(imageH)
contentView.addSubview(stackView)
//autolayout the stack view
let sH = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[stackView]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["stackView":stackView])
let sV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[stackView]-10-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["stackView":stackView])
contentView.addConstraints(sH)
contentView.addConstraints(sV)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
import UIKit
import CoreData
class ThingListTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: -Properties
var Things: [Thing] = []
var tableView: UITableView!
//var headerView = UIView!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// MARK: - LifeCycle
override func loadView() {
let view = UIView()
view.backgroundColor = .gray
self.view = view
}
override func viewDidLoad() {
super.viewDidLoad()
print("tableview loaded")
setupTable()
setupStack()
makeBarItems()
getData()
tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("tableview will appear")
getData()
tableView.reloadData()
checkforDone()
}
// MARK: -Methods
func makeBarItems(){
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "New", style: .plain, target: self, action: #selector(newTapped))
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"list-fat-7"), style: .plain, target: self, action: #selector(settingsButtonTapped))
navigationItem.title = "Things"
}
func getData() {
do {
Things = try context.fetch(Thing.fetchRequest())
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
print(String(describing: Things))
}
func setupTable() {
let frame = self.view.frame
tableView = UITableView(frame: frame)
tableView?.delegate = self
tableView?.dataSource = self
tableView.register(ThingCell.self, forCellReuseIdentifier: "Cell")
self.tableView?.backgroundColor = .white
self.tableView?.alpha = 0.6
self.tableView?.estimatedRowHeight = 100
}
func setupStack(){
headerView = UIView() // can do other things
let stackView = UIStackView(arrangedSubviews: [headerView, tableView])
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .fill
stackView.spacing = 10
stackView.translatesAutoresizingMaskIntoConstraints = false
// add some component constraints
let headHeight = headerView.heightAnchor.constraint(equalToConstant: 50)
stackView.addConstraints([headHeight])
view.addSubview(stackView)
//autolayout the stack view
let hSpacing: CGFloat = 0.0
let wSpacing: CGFloat = 0.0 //UIScreen.main.bounds.width/8
if #available(iOS 11.0, *) {
let guide = self.view.safeAreaLayoutGuide
stackView.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -wSpacing).isActive = true
stackView.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: wSpacing).isActive = true
stackView.topAnchor.constraint(equalTo: guide.topAnchor, constant: hSpacing).isActive = true
stackView.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: hSpacing).isActive = true
}
else {
let margins = view.layoutMarginsGuide
stackView.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: -wSpacing).isActive = true
stackView.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: wSpacing).isActive = true
stackView.topAnchor.constraint(equalTo: margins.topAnchor, constant: hSpacing).isActive = true
stackView.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: hSpacing).isActive = true
}
}
// MARK: - Button Methods
@objc func newTapped() {
print("newTapped")
}
@objc func settingsButtonTapped() {
print("settingsButtonTapped")
}
}
// MARK: - TableView Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Things.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let thing = Things[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ThingCell
// set cell contents
cell.goalImage = thing.image
cell.button1.title = thing.text1
cell.button2.title = thing.text2
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// get the selected item
let selected = Things[indexPath.row]
// do a transition
//let detailVC: DetailViewController? = DetailViewController()
// if detailVC != nil {
// detailVC?.modalPresentationStyle = .fullScreen
// detailVC?.thing = selected
// let navigationController = UINavigationController(rootViewController: detailVC!)
// // setup navBar.....
// navigationController.navigationBar.barTintColor = Style.majorColor
// navigationController.navigationBar.tintColor = Style.dkColor
// navigationController.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: Style.dkColor]
// navigationController.navigationBar.isTranslucent = true
// // Present it modally from the current controller
// present(navigationController, animated: true, completion: nil)
// }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment