例如,我有一个包含3个子视图的父视图.我以编程方式使用Layout Anchor并尝试实现以下布局
|--subview 1--|--subview 2--|--subview 3--|
三个子视图中的每一个具有相等的宽度.换一种说法,
subView1.width = subView2.width = subView3.width subView1.width + subView2.width + subView3.width = parentView.width
我知道我可以使用乘法器来设置subView 1和subView 2的宽度:
subView1.widthAnchor.constraintEqualToAnchor(contentView.widthAnchor, multiplier: 1/3).active = true subView2.widthAnchor.constraintEqualToAnchor(contentView.widthAnchor, multiplier: 1/3).active = true
和subView3可以使前导锚与subView2的尾随锚对齐.
但是,我在某处看到Interface Builder实际上可以将这三个宽度直接分配(不使用常量或乘数).是否可以通过编程方式对Layout Anchor进行相同的操作?如何?谢谢.
这是一套完整的锚点(我已经尝试过并且它有效):
// Create subView1 let subView1 = UIView() subView1.backgroundColor = UIColor.redColor() subView1.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(subView1) // Create subView2 let subView2 = UIView() subView2.backgroundColor = UIColor.blueColor() subView2.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(subView2) // Create subView3 let subView3 = UIView() subView3.backgroundColor = UIColor.greenColor() subView3.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(subView3) subView1.leadingAnchor.constraintEqualToAnchor(contentView.leadingAnchor).active = true subView1.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true subView1.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor).active = true subView2.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true subView2.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor).active = true subView3.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true subView3.trailingAnchor.constraintEqualToAnchor(contentView.trailingAnchor).active = true subView3.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor).active = true subView1.trailingAnchor.constraintEqualToAnchor(subView2.leadingAnchor).active = true subView2.trailingAnchor.constraintEqualToAnchor(subView3.leadingAnchor).active = true // Add equal width anchors subView1.widthAnchor.constraintEqualToAnchor(subView2.widthAnchor).active = true subView2.widthAnchor.constraintEqualToAnchor(subView3.widthAnchor).active = true
希望这可以帮助.:)