我有一个UIButton,我在故事板中设置了自动布局约束.我也有一个UIView,我在UIViewController的viewDidLoad方法中启动.我使这个视图(几乎)具有与UIButton相同的所有属性,但是当它在模拟器中运行它时它不会“粘住”到按钮上.这就是我所拥有的:
class ViewController: UIViewController { @IBOutlet weak var someButton: UIButton! func viewDidLoad() { super.viewDidLoad() let someView = UIView() someView.backgroundColor = UIColor.greenColor() someView.frame = someButton.bounds someView.frame.origin = someButton.frame.origin someView.autoresizingMask = someButton.autoresizingMask someView.autoresizesSubviews = true someView.layer.cornerRadius = someButton.layer.cornerRadius someView.clipsToBounds = true someView.userInteractionEnabled = false view.insertSubview(someView,belowSubview: someButton) } }
我想我错过了someView.auto布局约束?
编辑:我认为访问UIButton的约束会起作用,但它们似乎是一个空数组.故事板的约束是隐藏的吗?
someView.addConstraints(someButton.constraints)
谢谢.
解决方法
复制那种方式的约束失败,因为:
>故事板中的约束被添加到superview而不是按钮本身
>您尝试复制的约束是引用按钮而不是新视图
而不是复制约束,保持简单并创建新的约束并引用按钮:
let someView = UIView() someView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(someView) view.addConstraints([ NSLayoutConstraint(item: someView,attribute: .Leading,relatedBy: .Equal,toItem: someButton,multiplier: 1,constant: 0),NSLayoutConstraint(item: someView,attribute: .Trailing,attribute: .Top,attribute: .Bottom,constant: 0) ])