Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save froggomad/2ec6a728731835d3c7767b73abd3f949 to your computer and use it in GitHub Desktop.
Save froggomad/2ec6a728731835d3c7767b73abd3f949 to your computer and use it in GitHub Desktop.
import UIKit
class ViewControllerView: UIView {
private lazy var buttonStack: UIStackView = {
let stack = UIStackView(arrangedSubviews: [viewButton, alertButton])
stack.translatesAutoresizingMaskIntoConstraints = false
stack.spacing = 12
stack.axis = .vertical
return stack
}()
private lazy var viewButton: UIButton = makeButton(with: "Change backgroundColor")
private lazy var alertButton = makeButton(with: "Present Alert")
init(viewColor: UIColor) {
super.init(frame: .zero)
viewButton.addTarget(self, action: #selector(changeBackgroundColor), for: .touchUpInside)
subviews()
self.backgroundColor = viewColor
}
required init?(coder: NSCoder) {
fatalError("This is a programmatic view")
}
private func subviews() {
addSubview(buttonStack)
constraints()
}
private func constraints() {
NSLayoutConstraint.activate([
buttonStack.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -20),
buttonStack.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 20),
buttonStack.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -20)
])
}
/// Make a button with the given `title`, `backgroundColor`, and `UIButton.ButtonType`
private func makeButton(with title: String, backgroundColor: UIColor = .white, type: UIButton.ButtonType = .system) -> UIButton {
let button = UIButton(type: type)
button.setTitle(title, for: .normal)
button.backgroundColor = backgroundColor
button.layer.cornerRadius = 10
return button
}
@objc private func changeBackgroundColor() {
backgroundColor = .orange
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment