ios - @IBDesignable , NSLayoutConstraint 用于 super View 的比例乘数宽度?

标签 ios swift3 nslayoutconstraint

@IBDesignable ,

我正在尝试以编程方式设置“宽度为父级的 20%”:

@IBDesignable
class TwentyPercentExample:UIView {

    func setup() {
        let cWidth = NSLayoutConstraint(
            item: self,
            attribute: NSLayoutAttribute.width,
            relatedBy: NSLayoutRelation.equal,
            toItem: self.superview,
            attribute: NSLayoutAttribute.width,
            multiplier: 0.2,
            constant:0
        )
        addConstraint(cWidth)
        print("I seemed to added the width constraint....")
        updateConstraintsIfNeeded() // could be useful..
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setup()
    }

}

(因此,您将在 Storyboard 中添加一个 UIView,也许将其设置为锚定在 super View 的左侧,然后将类更改为 TwentyPercentExample。)

奇怪的是,这不起作用。如果你这样做:
multiplier: 1,
constant:100

它很好地将它实时设置在 Storyboard中,宽度为 100。改成
multiplier: 1,
constant:200

它工作正常,实时将其更改为 200 宽度。然而,这似乎不起作用:
multiplier: 0.2,
constant:0

我有没有toItem:错了,还是什么?这是怎么回事?

最佳答案

我怀疑问题是您在 init 中执行此操作当self.superviewnil .您应该等到将约束添加到 super View 之后再添加约束。也许在 didMoveToSuperview() ,尽管这可能会变得困惑,因为您需要考虑到它可以多次添加到 super View 中。

可能固定常量案例起作用的原因是因为它合法地有一个使用 nil 硬编码为 100 的约束。项目为 toItem:争论。

所以,这些中的任何一个

override func didMoveToSuperview() { setup() }
... or ...
override func layoutSubviews() { setup() }

func setup() {
    self.widthAnchor
      .constraint(equalTo: superview!.widthAnchor, multiplier: 0.2)
      .isActive = true
}

似乎工作:但似乎工作不规律并在 Xcode 中生成“代理崩溃”错误。

关于ios - @IBDesignable , NSLayoutConstraint 用于 super View 的比例乘数宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41524379/

相关文章:

ios - 在 ios9 上的 uiwebview 中显示 pdf 有时滚动会卡住

ios - xcode 6 - 红色约束

iOS - 如何水平居中放置未知数量的不同尺寸的 subview 。

ios - 视频 URL pathExtension find nil

ios - Xcode Swift - 返回 View 后继续动画

Swift 3 更改为 NSErrorPointer?

ios - Autolayout:原点和大小应根据宽度和高度因素改变

ios - Coreplot - 选择线下区域

ios - 如何以编程方式更改 View 大小?

ios - 在 iOS 上提升 Asio SSL 认证