Skip to content

Instantly share code, notes, and snippets.

@BrandonShega
Created November 30, 2016 14:23
Show Gist options
  • Save BrandonShega/12723a22fe51b4c37044827c33d66e02 to your computer and use it in GitHub Desktop.
Save BrandonShega/12723a22fe51b4c37044827c33d66e02 to your computer and use it in GitHub Desktop.
Modal View Controller with constraints
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
var str = "Hello, playground"
class MainViewController: UIViewController {
let button: UIButton = {
let button = UIButton(frame: .zero)
button.backgroundColor = .blue
button.setTitle("Press Me", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
init() {
super.init(nibName: nil, bundle: nil)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
view.backgroundColor = .white
view.addSubview(button)
button.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true
button.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30).isActive = true
button.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
button.heightAnchor.constraint(equalToConstant: 50).isActive = true
button.addTarget(self, action: #selector(showModal), for: .touchUpInside)
}
func showModal() {
let modalVC = ModalViewController()
present(modalVC, animated: true, completion: nil)
}
}
class ModalViewController: UIViewController {
let innerView: UIView = {
let innerView = UIView(frame: .zero)
innerView.backgroundColor = .red
innerView.translatesAutoresizingMaskIntoConstraints = false
return innerView
}()
init() {
super.init(nibName: nil, bundle: nil)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
view.backgroundColor = .white
view.addSubview(innerView)
innerView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 17).isActive = true
innerView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -17).isActive = true
innerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 17).isActive = true
innerView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -17).isActive = true
let tapGesture = UITapGestureRecognizer()
tapGesture.addTarget(self, action: #selector(closeModal))
innerView.addGestureRecognizer(tapGesture)
}
func closeModal() {
dismiss(animated: true, completion: nil)
}
}
let vc = MainViewController()
PlaygroundPage.current.liveView = vc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment