【问题标题】:Where to add subViews that I want floating in an NSScrollView using AutoLayout?在哪里添加我想使用 AutoLayout 在 NSScrollView 中浮动的子视图?
【发布时间】:2014-12-30 12:02:26
【问题描述】:

我有几个视图需要与我正在制作的 NSScrollView 的自定义子类协作。一种类型的视图需要相对于 NSScrollView 中的滚动完全固定,另一种类型的外壳需要相对于滚动固定在位置上,但允许内部内容随着滚动视图的变化而滚动(如电子表格中的列标题)例如)。

以下是在视图层次结构 AFAIK 中放置这些视图的选项:

  1. NSScrollView 的子视图(最有意义,但我收到以下错误: *** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: A multiplier of 0 or a nil second item together with a location for the first attribute creates an illegal constraint of a location equal to a constant. Location attributes must be specified in pairs)
  2. NSScrollView 的父视图的子视图(这似乎效果更好,但从设计角度来看感觉不对,因为我希望我的视图成为 scrollView 的一部分)

===

我还在网上不止一个地方读到,我将无法使用Visual Format Language 方法来设置我的约束,因为浮动约束不是相对于直接超级视图设置的。这是我在上面做错了什么的线索,因为第二种方法可以使用 VCL,而第一种方法需要手动创建 NSLayoutConstraint。

===

以下是我添加到我的 NSScrollView 子类的初始化程序中的 Swift 代码:

    topCorner = NSButton()
    topCorner.translatesAutoresizingMaskIntoConstraints = false
    topCorner.bezelStyle = NSBezelStyle.CircularBezelStyle  //.RecessedBezelStyle
    topCorner.setButtonType(NSButtonType.PushOnPushOffButton)
    topCorner.identifier = "topCorner"
    topCorner.title = "TC"
    self.addSubview(topCorner)

    thc = NSLayoutConstraint(item: self.topCorner, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.superview, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0.0)
    self.addConstraint(thc)

    thc1 = NSLayoutConstraint(item: self.topCorner, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 36.0)
    self.addConstraint(thc1)

    thc2 = NSLayoutConstraint(item: self.topCorner, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.superview, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0)
    self.addConstraint(thc2)

    thc3 = NSLayoutConstraint(item: self.topCorner, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 24.0)
    self.addConstraint(thc3)

只是为了进一步混淆,我得到的错误消息只有当我在代码中有约束 thc 和 thc2 时。 (尝试注释掉不同的约束以查看导致可怕错误文本的原因。)

【问题讨论】:

    标签: objective-c cocoa swift autolayout nsscrollview


    【解决方案1】:

    错误信息是由于在添加约束时没有创建self.superview的关系。

    由于无法将 thc 和 thc2 这两个约束添加到 NSScrollView,因此需要将它们添加到其父视图。

    虽然上面仍然没有产生我想要的结果,但它消除了运行时出现的两个错误。

    【讨论】:

      【解决方案2】:

      如果您尝试向不在视图层次结构中的视图添加约束,就会发生这种情况。自动布局限制。

      为了调试它,我找出了导致问题的以编程方式创建的约束。然后我调试到这一点,并在添加约束时检查约束中的 2 个视图都不是空的。其中之一是。我解决了这个问题,错误消失了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多