![](/img/trans.png)
[英]UIView in NSLayoutContraint does not conform to AnyObject in swift
[英]Simple NSLayoutContraint usage in Swift?
我正在為子視圖尋找一個簡單的Swift解決方案,以編程方式使用NSLayoutContraint填充超級視圖。 它應該很容易理解。 我覺得目前大多數答案都比需要的更復雜。
extension NSLayoutConstraint {
public static func simpleConstraints( view:NSView, direction:NSString = "H", padding1:Int = 0, padding2:Int = 0 ) -> [NSLayoutConstraint] {
view.translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint.constraintsWithVisualFormat("\(direction):|-\(padding1)-[view]-\(padding2)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":view])
return constraint
}
}
用法:
parent.addConstraints( NSLayoutConstraint.simpleConstraints(child, direction: "H") )
parent.addConstraints( NSLayoutConstraint.simpleConstraints(child, direction: "V") )
假設您已將translatesAutoresizingMaskIntoConstraints
設置為false
並將subview
添加為subview
的子view
,則可以設置四個約束,如下所示:
NSLayoutConstraint.activateConstraints([
subview.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor),
subview.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor),
subview.topAnchor.constraintEqualToAnchor(view.topAnchor),
subview.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor)
])
或者在Swift 3中:
NSLayoutConstraint.activate([
subview.leadingAnchor.constraint(equalTo: view.leadingAnchor),
subview.trailingAnchor.constraint(equalTo: view.trailingAnchor),
subview.topAnchor.constraint(equalTo: view.topAnchor),
subview.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
這是一個使用可視格式的簡單解決方案:
subview.translatesAutoresizingMaskIntoConstraints = false
let views = ["subview":subview]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[subview]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[subview]|", options: [], metrics: nil, views: views))
一個更簡單的解決方案,根本不使用自動布局:
subview.frame = view.bounds
subview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
結合Rob的建議和我的NSLayoutConstraint擴展概念,我已經確定了這一點,以便有一行簡單的“填充superview”命令:
extension NSLayoutConstraint {
public static func activateConstraintsEqualToSuperview(child: NSView) {
if ( child.superview == nil ) {
Swift.print("NSLayoutConstraint.fillSuperview() superview of child is nil")
return;
}
child.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activateConstraints( [
child.leadingAnchor.constraintEqualToAnchor( child.superview!.leadingAnchor ),
child.trailingAnchor.constraintEqualToAnchor( child.superview!.trailingAnchor ),
child.topAnchor.constraintEqualToAnchor( child.superview!.topAnchor ),
child.bottomAnchor.constraintEqualToAnchor( child.superview!.bottomAnchor )
])
}
}
用法:
NSLayoutConstraint.activateConstraintsEqualToSuperview(child)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.