Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save glennposadas/df43e50232d08c13a265180ec5936979 to your computer and use it in GitHub Desktop.
Save glennposadas/df43e50232d08c13a265180ec5936979 to your computer and use it in GitHub Desktop.
vertical uibutton
import UIKit
class ViewController: UIViewController {
var button: VerticalButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .red
button = VerticalButton(icon: .init(named: "ic_poll_results")!, title: "Results")
button.addTarget(self, action: #selector(boom), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(button)
NSLayoutConstraint.activate([
button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.widthAnchor.constraint(equalToConstant: 50),
button.heightAnchor.constraint(equalToConstant: 50),
])
}
@objc
func boom() {
print("boom")
}
}
/**
A custom `UIButton` that has custom label and imageView
which are both aligned vertically. Image at the top, label at the bottom.
*/
class VerticalButton: UIButton {
private(set) var icon: UIImage!
private(set) var title: String!
convenience init(icon: UIImage, title: String) {
self.init(frame: .zero)
self.icon = icon
self.title = title
layout()
}
override var isHighlighted: Bool {
didSet {
subviews.forEach {
$0.alpha = self.isHighlighted ? 0.6 : 1.0
}
}
}
}
private extension VerticalButton {
func layout() {
let imageView = UIImageView(image: icon)
imageView.isUserInteractionEnabled = false
imageView.contentMode = .scaleAspectFit
let titleLabel = UILabel()
titleLabel.font = .systemFont(ofSize: 14)
titleLabel.text = title
titleLabel.textAlignment = .center
titleLabel.isUserInteractionEnabled = false
let stackView = UIStackView(arrangedSubviews: [
imageView,
titleLabel
])
stackView.axis = .vertical
stackView.spacing = 4
stackView.isUserInteractionEnabled = false
stackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(stackView)
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: topAnchor),
stackView.bottomAnchor.constraint(equalTo: bottomAnchor),
stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor)
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment