Skip to content

Instantly share code, notes, and snippets.

@adamkaump
Last active May 15, 2022 16:14
Show Gist options
  • Save adamkaump/ed1b812ca8d3c22ce0f1f482e3d2ed0c to your computer and use it in GitHub Desktop.
Save adamkaump/ed1b812ca8d3c22ce0f1f482e3d2ed0c to your computer and use it in GitHub Desktop.
Some of my favorite convenience initializers for UIView subclass
import UIKit
extension UIView {
convenience init(_ maskIntoConstraints: Bool) {
self.init()
self.translatesAutoresizingMaskIntoConstraints = maskIntoConstraints
}
}
extension UILabel {
convenience init(text: String?, font: UIFont, color: UIColor? = nil, alignment: NSTextAlignment? = nil) {
self.init(false)
self.text = text
self.font = font
self.textColor = color
self.numberOfLines = 0
self.textAlignment = alignment ?? .left
}
}
extension UITextField {
convenience init(text: String?, font: UIFont) {
self.init(false)
self.text = text
self.font = font
self.translatesAutoresizingMaskIntoConstraints = false
}
}
extension UIScrollView {
convenience init(bounceVertical: Bool) {
self.init(false)
self.alwaysBounceVertical = bounceVertical
}
}
extension UIButton {
convenience init(title: String) {
self.init(false)
self.setTitle(title, for: .normal)
}
convenience init(title: String? = nil, target: Any?, action: Selector, for f: UIControl.Event? = .touchUpInside) {
self.init(false)
self.setTitle(title, for: .normal)
addTarget(target, action: action, for: f!)
}
convenience init(image: UIImage?, target: Any?, action: Selector, for f: UIControl.Event? = .touchUpInside) {
self.init(false)
self.setImage(image, for: .normal)
addTarget(target, action: action, for: f!)
}
}
extension UITableView {
convenience init(style: Style, dataSource: UITableViewDataSource, delegate: UITableViewDelegate?) {
self.init(frame: .zero, style: style)
self.dataSource = dataSource
self.delegate = delegate
self.translatesAutoresizingMaskIntoConstraints = false
}
}
extension UIImageView {
convenience init(_ image: UIImage?, tint: UIColor? = nil) {
self.init(false)
self.image = image
self.tintColor = tint
}
convenience init(_ contentMode: ContentMode) {
self.init(false)
self.contentMode = contentMode
}
convenience init(_ image: UIImage?, contentMode: ContentMode) {
self.init(false)
self.image = image
self.contentMode = contentMode
}
}
extension UISlider {
convenience init(value: Float, minValue: Float, maxValue: Float) {
self.init(false)
self.minimumValue = minValue
self.maximumValue = maxValue
self.value = value
}
}
extension UISegmentedControl {
convenience init(titles: [String], selectedIndex: Int? = nil) {
self.init(items: titles)
translatesAutoresizingMaskIntoConstraints = false
if let index = selectedIndex {
self.selectedSegmentIndex = index
}
}
}
extension UIStackView {
convenience init(spacing: CGFloat, axis: NSLayoutConstraint.Axis) {
self.init(false)
self.spacing = spacing
self.axis = axis
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment