Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save froggomad/6299abb474e038f58131edfdee60c4e1 to your computer and use it in GitHub Desktop.
Save froggomad/6299abb474e038f58131edfdee60c4e1 to your computer and use it in GitHub Desktop.
//
// ViewControllerView.swift
// TinyViewController
//
// Created by Kenneth Dubroff on 7/9/21.
//
import UIKit
class ViewControllerView: UIView {
var target: Any?
var selector: Selector
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", target: self, selector: #selector(changeBackgroundColor))
private lazy var alertButton = makeButton(with: "Present Alert", target: target, selector: selector)
init(viewColor: UIColor, target: Any?, selector: Selector) {
self.target = target
self.selector = selector
super.init(frame: .zero)
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, target: Any?, selector: Selector) -> UIButton {
let button = UIButton(type: type)
button.setTitle(title, for: .normal)
button.addTarget(target, action: selector, for: .touchUpInside)
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