他の方が取り上げていたら
四隅のアンカー作成
extension UIView {
func addEdgeConstraint() {
guard let superview = self.superview else {
return
}
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.topAnchor.constraint(equalTo: superview.topAnchor),
self.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
self.trailingAnchor.constraint(equalTo: superview.trailingAnchor),
self.bottomAnchor.constraint(equalTo: superview.bottomAnchor),
])
}
func addEdgeSafeAreaConstraint() {
guard let superview = self.superview else {
return
}
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.topAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.topAnchor),
self.leadingAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.leadingAnchor),
self.trailingAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.trailingAnchor),
self.bottomAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.bottomAnchor),
])
}
}
使い方
class ViewController: UIViewController {
let imageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
imageView.addEdgeSafeAreaConstraint()
}
}
インスタンス生成時のプロパティ編集
protocol Layout: UIView {}
extension UIView: Layout {}
extension Layout {
func layout(_ layout: (Self) -> Void) -> Self {
layout(self)
return self
}
}
使い方
class ViewController: UIViewController {
let label: UILabel = UILabel()
.layout {
$0.textColor = .white
}
}
もっと上手に書ける方法があったら教えていただけると非常に嬉しいです