【问题标题】:Overwrite storyboard Height and Width for UIView覆盖 UIView 的故事板高度和宽度
【发布时间】:2015-09-07 06:53:13
【问题描述】:

我一直在尝试为我的应用设计一个可重用的组件。它主要用于学习目的。

我试图以编程方式设置约束,但 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))
    }


}

【问题讨论】:

  • 首先你应该给你的 TOHeader 添加顶部约束。
  • 刚刚尝试添加这个顶级约束:addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 0.0)),它确实让我的应用程序崩溃
  • 您的顶级约束在超级视图或其他视图之间没有关系,请尝试像 superview!.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: .Equal, toItem: superview!, attribute: .Top, multiplier: 1.0, constant: 0.0))
  • 效果很好,谢谢。但是宽度和高度约束仍然没有被应用,因为它们被Interface Builder 打破了。任何想法 ?也许有更好的方法
  • 一般来说,我更喜欢在超级视图中添加约束而不是在视图中。当您将 TOHeader 添加到您的视图时,您应该在调用 addSubview: 方法后添加您的约束

标签: ios iphone swift uiview


【解决方案1】:

您可以在情节提要中添加约束。然后 Ctrl 将它们中的每一个从 View Hierarchy 拖到类中,为它们创建出口。然后您可以从代码中访问和更改它们,请参见下面的 viewDidLoad 方法

【讨论】:

  • 这不是@whitep4nther 所要求的。
猜你喜欢
  • 1970-01-01
  • 2011-04-03
  • 2014-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-04
  • 2016-03-18
  • 1970-01-01
相关资源
最近更新 更多