2015-09-07 63 views
0

我一直在试图为我的应用程序设计一个可重用组件。它主要用于学习目的。覆盖故事板UIView的高度和宽度

我试图以编程方式设置的限制,但Interface Builder不断增加自动约束:

<NSIBPrototypingLayoutConstraint:0x7fae02731800 'IB auto generated at build time for view with fixed frame' H:[_1.TOHeader:0x7fae02718c20(89)]> 

那是打破我的。

这里是我的代码:

import UIKit 

class TOHeader: UIView { 

    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     println("init aDecoder") 
     self.backgroundColor = UIColor(red: 255, green: 0, blue: 0, alpha: 1) 
     self.setTranslatesAutoresizingMaskIntoConstraints(false) 
    } 

    override func willMoveToSuperview(newSuperview: UIView?) { 
     super.willMoveToSuperview(newSuperview) 
     println("willMoveToSuperview()") 
    } 

    override func didMoveToSuperview() { 
     super.didMoveToSuperview() 

     superview!.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Left, relatedBy: .Equal, toItem: superview!, attribute: .Left, multiplier: 1.0, constant: 0.0)) 
     superview!.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: .Equal, toItem: superview!, attribute: .Width, multiplier: 1.0, constant: 0.0)) 
     addConstraint(NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 42)) 
    } 


} 
+1

首先,你应该添加顶部约束你TOHeader。 –

+0

试着添加这个顶部约束:'addConstraint(NSLayoutConstraint(item:self,attribute:NSLayoutAttribute.Top,relatedBy:.Equal,toItem:nil,attribute:.NotAnAttribute,multiplier:1.0,constant:0.0)''让我的应用程序崩溃 – whitep4nther

+1

你最上面的约束没有superview或其他视图之间的关系尝试像这样'superview!.addConstraint(NSLayoutConstraint(item:self,attribute:NSLayoutAttribute.Top,relatedBy:.Equal,toItem:superview !,属性:.Top,乘数:1.0,常数:0.0))' –

回答

0

您可以在故事板添加的约束。然后按Ctrl将其中的每一个从View Hierarchy拖放到该类中,以便为它们创建出口。然后,您可以访问和他们更改代码中的,请参阅下面的viewDidLoad方法

enter image description here

+0

这不是@ whitep4nther问的问题。 –