Skip to content

Instantly share code, notes, and snippets.

@ClouddJR
Created June 29, 2023 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ClouddJR/76569dbc98f5179de6ff1cd3c453dc4c to your computer and use it in GitHub Desktop.
Save ClouddJR/76569dbc98f5179de6ff1cd3c453dc4c to your computer and use it in GitHub Desktop.
import Foundation
import UIKit
final class ContentView: UIView {
private lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.spacing = 16.0
stackView.distribution = .equalSpacing
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
private lazy var label: UILabel = {
let label = UILabel()
label.text = "Lorem ipsum dolor"
label.font = UIFont.preferredFont(forTextStyle: .body)
label.adjustsFontForContentSizeCategory = true
return label
}()
private lazy var button: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Action", for: .normal)
button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body)
button.titleLabel?.adjustsFontForContentSizeCategory = true
return button
}()
init() {
super.init(frame: .zero)
stackView.addArrangedSubview(label)
stackView.addArrangedSubview(button)
addSubview(stackView)
stackView.pinEdges(to: self)
}
@available(*, unavailable)
required init(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
updateStackViewAxis()
}
private func updateStackViewAxis() {
let maxWidth = bounds.width
let labelWidth = label.sizeThatFits(frame.size).width
let buttonWidth = button.sizeThatFits(frame.size).width
let spacing = stackView.spacing
let isHorizontal = maxWidth > labelWidth + buttonWidth + spacing
stackView.axis = isHorizontal ? .horizontal : .vertical
stackView.alignment = isHorizontal ? .firstBaseline : .leading
stackView.invalidateIntrinsicContentSize()
}
}
private extension UIView {
func pinEdges(to other: UIView) {
leadingAnchor.constraint(equalTo: other.leadingAnchor).isActive = true
trailingAnchor.constraint(equalTo: other.trailingAnchor).isActive = true
topAnchor.constraint(equalTo: other.topAnchor).isActive = true
bottomAnchor.constraint(equalTo: other.bottomAnchor).isActive = true
}
}
import UIKit
class ViewController: UIViewController {
private let contentView = ContentView()
override func viewDidLoad() {
super.viewDidLoad()
contentView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(contentView)
contentView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16.0).isActive = true
view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 16.0).isActive = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment