プログラムでUIをあまり実行していませんが、UIViewがあり、UILabelをUIViewの左上隅に制約し、次に別のUILabelを右上隅に制約したいと考えています。私はGUIでこれを行う方法を完全に知っていますが、これを純粋に迅速に/プログラムで行うにはどうすればよいのか疑問に思いました。
これはNSLayoutConstraint
クラスで行われます。
まず、ラベルをサブビューとして追加します。
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
これは、サブビューに制約を簡単に追加するための私の拡張機能です。ここであなたが勉強するための主な方法はfunc pin(firstSubview subview1:UIView, firstEdge edge1:NSLayoutAttribute, secondSubview subview2:UIView, secondEdge edge2:NSLayoutAttribute, with constant:Float)
extension UIView {
func pinSubview(_ subview:UIView, toEdge edge:NSLayoutAttribute, withConstant constant:Float) {
self.pinSubviews(self, subview2: subview, toEdge: edge, withConstant: constant)
}
func pinSubviews(_ subview1:UIView, subview2:UIView, toEdge edge:NSLayoutAttribute, withConstant constant:Float) {
pin(firstSubview: subview1, firstEdge: edge, secondSubview: subview2, secondEdge: edge, with: constant)
}
func pin(firstSubview subview1:UIView, firstEdge edge1:NSLayoutAttribute, secondSubview subview2:UIView, secondEdge edge2:NSLayoutAttribute, with constant:Float) {
let constraint = NSLayoutConstraint(item: subview1, attribute: edge1, relatedBy: .equal, toItem: subview2, attribute: edge2, multiplier: 1, constant: CGFloat(constant))
self.addConstraint(constraint)
}
func pinSubview(_ subview:UIView, withHeight height:CGFloat) {
let height = NSLayoutConstraint(item: subview, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)
self.addConstraint(height)
}
func pinSubview(_ subview:UIView, withWidth width:CGFloat) {
let width = NSLayoutConstraint(item: subview, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width)
self.addConstraint(width)
}
}
次に、非常に簡単な使用法があります。
self.view.pinSubview(label, toEdge: .left, withConstant: 0)
self.view.pinSubview(label, toEdge: .top, withConstant: 0)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加