Embed
/// Embed a View to certain anchors (top, bottom, leading, trailing)
/// - Parameters:
/// - withPadding: The amount of space between the embedded view and this view
/// - closure: A trailing closure that accepts a view
@discardableResult
func embed(withPadding padding: [Padding],
_ closure: () -> NSView) -> Self {
let viewToEmbed = closure()
viewToEmbed.translatesAutoresizingMaskIntoConstraints = false
addSubview(viewToEmbed)
NSLayoutConstraint.activate(
padding.map {
switch $0 {
case .leading(let constant):
return viewToEmbed.leadingAnchor.constraint(equalTo: leadingAnchor, constant: CGFloat(constant))
case .trailing(let constant):
return viewToEmbed.trailingAnchor.constraint(equalTo: trailingAnchor, constant: CGFloat(-constant))
case .top(let constant):
return viewToEmbed.topAnchor.constraint(equalTo: topAnchor, constant: CGFloat(constant))
case .bottom(let constant):
return viewToEmbed.bottomAnchor.constraint(equalTo: bottomAnchor, constant: CGFloat(-constant))
}
}
)
return self
}
Stack
/// Embed a Stack
/// - Parameters:
/// - withSpacing: The amount of spacing between each child view
/// - padding: The amount of space between this view and its parent view
/// - alignment: The layout of arranged views perpendicular to the stack view’s axis (source: NSStackView.Alignment)
/// - distribution: The layout that defines the size and position of the arranged views along the stack view’s axis (source: NSStackView.Distribution)
/// - axis: Keys that specify a horizontal or vertical layout constraint between objects (source: NSUserInterfaceLayoutOrientation)
/// - closure: A trailing closure that accepts an array of views
@discardableResult
func stack(withSpacing spacing: Float = 0,
padding: [Padding],
alignment: NSLayoutConstraint.Attribute = .top,
distribution: NSStackView.Distribution = .fill,
axis: NSUserInterfaceLayoutOrientation,
_ closure: () -> [NSView?]) -> Self {
let viewsInVStack = closure()
.compactMap { $0 }
let stackView = NSStackView(views: viewsInVStack)
stackView.spacing = CGFloat(spacing)
stackView.alignment = alignment
stackView.distribution = distribution
stackView.orientation = axis
embed(withPadding: padding) {
stackView
}
return self
}
SwiftAK Example
import Cocoa
import SwiftAK
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.center {
NSView().vstack {
[
NSView(backgroundColor: .red)
.frame(height: 100, width: 100)
.padding()
.background(color: .yellow),
NSText()
.configure {
$0.string = "Hello World!"
}
.background(color: .blue)
.frame(height: 60, width: 100)
]
}
}
}
}