2016-03-04 72 views
3

我有一个UIButton,我在故事板中设置了自动布局约束。我也有一个UIView,我在UIViewControllerviewDidLoad方法中发起。我使这个视图具有(几乎)所有与UIButton相同的属性,但是当它在模拟器中运行时,它不会“粘”到按钮上。这里就是我:Swift:以编程方式将自动布局约束从一个视图复制到另一个视图

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) 
    } 

} 

我想我错过了。汽车布局约束?

编辑:我认为访问UIButton的约束会工作,但他们似乎是一个空阵列。故事板约束是隐藏的吗?

someView.addConstraints(someButton.constraints) 

谢谢。

回答

2

复制约束的方式失败,因为:

  • 在故事板的限制被添加到上海华而不是按钮本身
  • 约束您尝试复制所引用的按钮,而不是新鉴于

,而不要照搬约束的保持它的简单和创造新的和引用按钮:

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) 
    ]) 
+0

你可以访问superview中的按钮约束吗?我很喜欢控制拖动:-) – Alex

+0

你可以但为什么你会喜欢这样做?基本上你需要循环访问superview的约束,并用按钮比较firstItem和secondItem。不是一个特别安全的方法。 –

+0

你是对的我想 - 我只是认为你可以得到更多的手工精度。需要修改我的自动布局... – Alex

相关问题