簡體   English   中英

將實例化的UIView從NIB約束到其他UIView

[英]Constraining instantiated UIView from NIB to other UIView

我在向從NIB到另一個UIView的新實例化UIView添加約束時遇到問題。

我想做的確切是這樣的:

  1. 從NIB文件加載UIView。 (完成)
  2. 在第一個NIB文件中有一個UIView組件,它充當另一個UIView的容器。 灰色背景。 (完成)
  3. 從另一個NIB文件加載第二個UIView(綠色背景),並將其放在第一個UIView(灰色的)中。 (這是問題所在)我所說的里面完全是在容器的位置。 容器UIView為300x280(灰色背景),外部UIView也為綠色背景。

我可以在第一個UIView中添加第二個UIView,因為我可以看到它,但是約束已關閉。 第一個UIView使用AutoLayout來容納自身,但第二個UIView則不使用第二個UIView中的組件進行布局。

觀察:

如果將背景色添加到第二個UIView時將其添加到容器UIView中,則框架非常合適,但是組件不完美,它們總是看起來不對。 我嘗試過clipToBounds = true ,它通過將組件保留在UIView中來工作,但是我找不到將所有組件(UITextField,UIButton等)與兩個UIView對齊的方法。

屏幕截圖:

在此處輸入圖片說明

容器/第一個UIView的代碼:

override func viewDidAppear(animated: Bool)
{
    super.viewDidAppear(animated)

    // loginView  = IS THE UIView in the second NIB.        
    // otherViews = IS THE UIView CONTAINER in the first NIB.

    let loginView = BCAKLoginView() // LOAD NIB FILE
    self.loginView.frame  = self.otherViews.bounds
    self.loginView.hidden = false
    self.loginView.backgroundColor = UIColor.redColor()
    self.loginView.clipsToBounds = true

    self.otherViews.addSubview(loginView) // HERE I ADD THE SECOND NIB TO UIView.

    let constraintLeading = NSLayoutConstraint.init(
        item: self.loginView,
        attribute: NSLayoutAttribute.Leading,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.otherViews,
        attribute: NSLayoutAttribute.Leading,
        multiplier: 1.0,
        constant: 0.0
    )
    let constraintWidth = NSLayoutConstraint.init(
        item: self.loginView,
        attribute: NSLayoutAttribute.Width,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.otherViews,
        attribute: NSLayoutAttribute.Width,
        multiplier: 1.0,
        constant: 0.0
    )
    let constraintTop = NSLayoutConstraint.init(
        item: self.loginView,
        attribute: NSLayoutAttribute.Top,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.otherViews,
        attribute: NSLayoutAttribute.Top,
        multiplier: 1.0,
        constant: 0.0
    )
    let constraintBottom = NSLayoutConstraint.init(
        item: self.loginView,
        attribute: NSLayoutAttribute.Bottom,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.otherViews,
        attribute: NSLayoutAttribute.Bottom,
        multiplier: 1.0,
        constant: 0.0
    )

    self.otherViews.addConstraint(constraintLeading)
    self.otherViews.addConstraint(constraintWidth)
    self.otherViews.addConstraint(constraintTop)
    self.otherViews.addConstraint(constraintBottom)
}

好吧,回答我自己的問題..

問題是當我實例化第二個NIB文件(UIView)時。 initWithFrame:initWithCoder: 我將其添加為自己的子視圖,因此在loginViewotherViews之間添加了一個額外的UIView。 就是這樣...當我刪除這個多余的視圖時,一切都對齊了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM