我有一个没有框架的框,因此它的中心和大小为0。
let blackBox = UIView()
blackBox.backgroundColor = .blackColor()
blackBox.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(blackBox)
view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 0.1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 0.5, constant: 0))
view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0))
无论如何使用自动布局将中心子视图插入blackBox
而不使用,或者是否有更整洁的方式我可以/应该使用它。我能看到这种情况的唯一方法是:
let blueBox = UIView()
blackBox.addSubview(blueBox)
blueBox.translatesAutoresizingMaskIntoConstraints = false
blueBox.backgroundColor = UIColor.blueColor()
view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .CenterX, relatedBy: .Equal, toItem: blackBox, attribute: .CenterX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .CenterY, relatedBy: .Equal, toItem: blackBox, attribute: .CenterY, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .Width, relatedBy: .Equal, toItem: blackBox, attribute: .Width, multiplier: 0.4, constant: 0))
view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .Height, relatedBy: .Equal, toItem: blackBox, attribute: .Height, multiplier: 0.4, constant: 0))
答案 0 :(得分:0)
我个人会使用var bluebox = UIView(frame: CGRECT)
并相应地设置CGRect
。