【问题标题】:Autolayout with xib and storyboard won’t use my constraints带有 xib 和情节提要的自动布局不会使用我的约束
【发布时间】:2015-06-17 11:26:41
【问题描述】:

我正在尝试创建一个可重用的视图 (xib) 并在我的故事板中使用它和自动布局。问题是它似乎没有使用我在情节提要上为它设置的约束。

所以我真正的基本 IOS 项目包含:

  • MyView.swift
  • MyView.xib
  • Main.storyboard
  • ViewController.swift

MyView 类以正确的方式连接到 xib 文件:

import UIKit

class MyView: UIView {

    @IBOutlet var View: UIView!

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        NSBundle.mainBundle().loadNibNamed("MyView", owner: self, options: nil)
        self.addSubview(self.View);
    }
}

在我的故事板中,我添加了一个带有 2 个简单高度/宽度约束的 UIView (CustomClass=MyView)。当我运行应用程序时,视图不会根据这些约束调整大小。它使用 xib 中的高度/宽度属性呈现。

是否有人知道如何使我的自定义视图符合我在情节提要中设置的约束?

【问题讨论】:

    标签: ios storyboard autolayout constraints xib


    【解决方案1】:

    您是说当您使用 xib 加载它的视图时,您的 UIView 是使用 xib 的高度和宽度呈现的?意思是,xib 是您在运行模拟器时唯一看到的东西?如果是这样,我认为简单的解决方案是创建一个加载 xib 的附加 UIView。使 NewView 成为 MyView 的子视图 这样您就有了 MyView -> NewView(加载了 xib)。

    对不起,如果那是一种方式。在没有看到它的情况下理解你的意思有点困难。也许抛出一两个屏幕截图。会将此作为评论而不是答案发布,但我还没有声誉。

    【讨论】:

      【解决方案2】:

      这应该有帮助

      var contentView =  NSBundle.mainBundle().loadNibNamed("MyView", owner: self, options: nil)
      contentView.setTranslatesAutoresizingMaskIntoConstraints(false)
      self.addSubview(contentView)
      
          var constTop:NSLayoutConstraint = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0);
          self.view.addConstraint(constTop);
      
          var constBottom:NSLayoutConstraint = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0);
          self.view.addConstraint(constBottom);
      
          var constLeft:NSLayoutConstraint = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0);
          self.view.addConstraint(constLeft);
      
          var constRight:NSLayoutConstraint = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0);
          self.view.addConstraint(constRight);
      

      【讨论】:

        猜你喜欢
        • 2014-12-04
        • 2019-05-02
        • 2015-05-29
        • 2014-10-12
        • 2017-08-09
        • 2014-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多