简体   繁体   English

在Swift中以编程方式在两个子视图之间添加约束

[英]Add constraints between two sub views programmatically in Swift

I have two subviews that I created, one in Storyboard one with code, I want to anchor the second view (created with code) to the first view (in storyboard) with some constraints so that the second view sits below the first view: 我创建了两个子视图,一个在故事板中,一个带有代码,我想将第二个视图(使用代码创建)锚定到第一个视图(在故事板中),并带有一些约束,以便第二个视图位于第一个视图下方:

class ViewController: UIViewController{
    @IBOutlet weak var view1: UIView!
    override func viewDidLoad(){
        super.viewDidLoad()
        setUp()
    }

    func setUp(){

        var view2 = UIView()
        view2.setTranslatesAutoresizingMaskIntoConstraints(false)
        view2.frame = CGRectMake(10,10,10,10)

        self.view.addSubview(view2)
        self.view.addConstraint(NSLayoutConstraint(item: view1, attribute: NSLayoutAttribute.TopMargin, relatedBy: NSLayoutRelation.Equal, toItem: view2, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10))
    }
}

The problem is that I got an error saying When added to a view, the constraint's items must be descendants of that view . 问题是我收到一条错误消息,说When added to a view, the constraint's items must be descendants of that view Is it bad practice to have some views in storyboard and others in code? 在情节提要中有一些视图并在代码中有其他视图是不好的做法吗?

You have a few problems. 你有几个问题。

First, the error means that view1 and view2 are not both part of self.view 's view hierarchy. 首先,该错误意味着view1view2都不是self.view的视图层次结构的一部分。 This is probably because view1 hasn't been decoded from the storyboard yet. 这可能是因为view1尚未从情节view1中解码出来。 Try moving this code from viewDidLoad() to awakeFromNib() , which is when they're guaranteed to have been loaded. 尝试将这段代码从viewDidLoad()移至awakeFromNib() ,这是确保已加载它们的时间。

Second, you're trying to set the view's frame: 其次,您尝试设置视图的框架:

view2.frame = CGRectMake(10,10,10,10)

This frame will get overwritten by the layout engine making it pointless. 该框架将被布局引擎覆盖,使其毫无意义。 Delete this line. 删除此行。

If you're going to use auto-layout, you need to unambiguously specify both the size (height & width) and position (x & y) of the view. 如果要使用自动布局,则需要明确指定视图的大小(高度和宽度)和位置(x和y)。 The constraint you added only specifies the y-origin, so you also need to add more constraints (probably 3 more) to specify the x-origin, the width, and the height, which are currently undefined. 您添加的约束仅指定了y方向,因此您还需要添加更多约束(可能再增加3个)来指定x方向,宽度和高度,这些约束当前未定义。


Is it bad practice to have some views in storyboard and others in code? 在情节提要中有一些视图并在代码中有其他视图是不好的做法吗?

No, it's common. 不,这很常见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM