Skip to content

Instantly share code, notes, and snippets.

@eivindml
Created October 6, 2017 08:24
Show Gist options
  • Save eivindml/f6654cb82a163805887cd834c70b0b56 to your computer and use it in GitHub Desktop.
Save eivindml/f6654cb82a163805887cd834c70b0b56 to your computer and use it in GitHub Desktop.
import UIKit
protocol HabitsViewDelegate: class {
func habitsView(_ habitsView: HabitsView, didSelectAddButton button: UIButton)
}
class HabitsView: UIView {
weak var delegate: HabitsViewDelegate?
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
private lazy var addButton: AddButton = {
let button = AddButton()
button.addTarget(self, action: #selector(addButtonAction(button:)), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubviewsAndConstraints()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addSubviewsAndConstraints() {
addSubview(tableView)
addSubview(addButton)
tableView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
tableView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
addButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16).isActive = true
addButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -16).isActive = true
addButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
addButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
@IBAction func addButtonAction(button: UIButton) {
delegate?.habitsView(self, didSelectAddButton: button)
}
}
@eivindml
Copy link
Author

eivindml commented Oct 6, 2017

The controller is like this:

class HabitsController: UIViewController {

    lazy var addHabitController: AddHabitController = {
        let addHabitController = AddHabitController()
        addHabitController.modalTransitionStyle = .crossDissolve
        // addHabitController.delegate = self

        return addHabitController
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func loadView() {
        let view = HabitsView(frame: UIScreen.main.bounds)
        view.delegate = self
        self.view = view
    }
}

extension HabitsController: HabitsViewDelegate {

    func habitsView(_: HabitsView, didSelectAddButton _: UIButton) {
        present(addHabitController, animated: true)
    }
}

@eivindml
Copy link
Author

eivindml commented Oct 6, 2017

Ideally I would set the delegate the same place I set the HabitsViewDelegate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment