EasyAnchor is a small extension that save time when anchoring view using AutoLayout.
It's a small and one line of code, but it's annoy that we need to specify translatesAutoresizingMaskIntoConstraints = false every time to use AutoLayout. With EasyAnchor, we resolve that annoying issue by using:
button.layout {
view.addSubview($0)
$0.setWidth(100)
$0.setHeight(50)
$0.left()
$0.bottom(constraint: redView.bottomAnchor, 0)
}
or with chaining:
button.layout {
view.addSubview($0)
$0.top().left().right().bottom()
}
or fill superview:
button.layout {
view.addSubview($0)
$0.fill()
}
or fill superview with insets:
button.layout {
view.addSubview($0)
$0.fill(insets: UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16))
}
or center superview:
button.layout {
view.addSubview($0)
$0.center()
}
or center vertically:
button.layout {
view.addSubview($0)
$0.centerY()
}
// With some padding
button.layout {
view.addSubview($0)
$0.centerY(50)
}
// With some padding from specific constraint
button.layout {
view.addSubview($0)
$0.centerY(constraint: redView.centerYAnchor, 10)
}
or center horizontally:
button.layout {
view.addSubview($0)
$0.centerX()
}
// With some padding
button.layout {
view.addSubview($0)
$0.centerX(50)
}
// With some padding from specific constraint
button.layout {
view.addSubview($0)
$0.centerX(constraint: redView.centerXAnchor, 10)
}
A class based building block, enable the shorthand syntax just after the object is initialized. It's common that we create some view and configure it with default closure like this:
let okButton: UIButton = {
let button = UIButton()
button.backgroundColor = UIColor.blue
button.setTitleColor(UIColor.white, for: .normal)
button.setTitle("OK", for: .normal)
button.layer.cornerRadius = 8
return button
}()
Here is shorthand syntax for above code.
let okButton = UIButton().decorate {
$0.backgroundColor = .blue
$0.setTitleColor(.white, for: .normal)
$0.setTitle("OK", for: .normal)
$0.layer.cornerRadius = 8
}
To enable or disable AutoLayout for specific view:
button.useAutoLayout = true // enable
button.useAutoLayout = false // disable
Copy EasyAnchor.swift
and Config.swift
to your project, or
pod 'EasyAnchor', :git => 'https://github.com/PhanithNY/EasyAnchor.git'
From Xcode menu bar:
- File
- Swift Packages
- Add Package Dependency...
- Paste the repo url
https://github.com/PhanithNY/EasyAnchor.git
PhanithNY, [email protected]
EasyAnchor is available under the MIT license. See the LICENSE file for more info.