use*_*583 3 ios nslayoutconstraint swift ios-autolayout
下面我列出了一些代码供您结账.我正在尝试自定义UIView并添加另一个自定义子视图.这个子视图应该以这样的方式约束到父视图,它基本上只是在相同的维度上放置,而父级只是作为包装器.
NSLayoutConstraint到目前为止,我已尝试使用和失败的悲惨.视图从未真正显示出来.我有一个left,right,bottom和top约束,它应与父视图对齐.
第一个问题是,有人请在使用以下方法时解释或纠正我的逻辑.我想到的项目参数是你想为(customViewChild)设置约束的实际视图.该属性是说我希望my的左边缘customViewChild用于此约束.在relatedBy看起来很简单的,虽然我可能是错的,最后的toItem指向自我这是我CustomViewParent这也有一个.left属性地说,我希望我的孩子和家长的左边缘对齐.这个逻辑有缺陷还是我做错了什么?
NSLayoutConstraint(item: customViewChild!,
attribute: .left,
relatedBy: .equal,
toItem: self,
attribute: .left,
multiplier: 1.0,
constant: 0.0)
Run Code Online (Sandbox Code Playgroud)
我知道下面的例子很容易用IB完成,但我想了解NSLayoutConstraint,所以请提供相关答案.最后,如果有人能够真正纠正这个代码,那么我有一个有效的例子,那将是非常棒的.
class CustomViewParent: UIView {
var customViewChild: UIView?
override init(frame: CGRect) {
super.init(frame: frame)
setConstraints()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setConstraints()
}
func setConstraints() {
customViewChild = UIView()
addSubview(customViewChild!)
customViewChild?.translatesAutoresizingMaskIntoConstraints = false
let leftConstraint = NSLayoutConstraint(item: customViewChild!,
attribute: .left,
relatedBy: .equal,
toItem: self,
attribute: .left,
multiplier: 1.0,
constant: 0.0).isActive = true
let rightConstraint = NSLayoutConstraint(item: customViewChild!,
attribute: .right,
relatedBy: .equal,
toItem: self,
attribute: .right,
multiplier: 1.0,
constant: 0.0).isActive = true
let topConstraint = NSLayoutConstraint(item: customViewChild!,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: 0.0).isActive = true
let bottomConstraint = NSLayoutConstraint(item: customViewChild!,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0).isActive = true
customViewChild.addConstraint([leftConstraint, rightConstraint, topConstraint, bottomConstraint]);
}
}
Run Code Online (Sandbox Code Playgroud)
您可能会发现这更容易,更易读......
func setConstraints() {
if customViewChild == nil {
customViewChild = UIView()
addSubview(customViewChild!)
customViewChild?.translatesAutoresizingMaskIntoConstraints = false
customViewChild?.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
customViewChild?.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
customViewChild?.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
customViewChild?.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}
}
Run Code Online (Sandbox Code Playgroud)