我有一个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, attribute: .Leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: someView, attribute: .Trailing, relatedBy: .Equal, toItem: someButton, attribute: .Trailing, multiplier: 1, constant: 0), NSLayoutConstraint(item: someView, attribute: .Top, relatedBy: .Equal, toItem: someButton, attribute: .Top, multiplier: 1, constant: 0), NSLayoutConstraint(item: someView, attribute: .Bottom, relatedBy: .Equal, toItem: someButton, attribute: .Bottom, multiplier: 1, constant: 0) ])