Created
November 30, 2016 14:23
-
-
Save BrandonShega/12723a22fe51b4c37044827c33d66e02 to your computer and use it in GitHub Desktop.
Modal View Controller with constraints
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
//: 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