我有几个 View 需要与我正在制作的 NSScrollView 的自定义子类协作。一种类型的 View 需要相对于 NSScrollView 中的滚动完全固定,另一种类型需要将其外壳固定在相对于滚动的位置,但允许内部内容随着 ScrollView 的变化而滚动(如电子表格中的列标题例如)。
以下是在 View 层次结构 AFAIK 中放置这些 View 的选项:
- NSScrollView 的 subview (最有意义但我收到以下错误:
*** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: 0 或 nil 第二项的乘数与第一个属性的位置一起创建位置等于的非法约束到一个常数。位置属性必须成对指定)
- NSScrollView 的 super View 的 subview (这似乎工作得更好,但从设计的角度来看感觉不对,因为我希望我的 View 成为 ScrollView 的一部分)
===
我还在网上不止一个地方读到我将无法使用Visual Format Language
方法来设置我的约束,因为 float 约束不是相对于直接设置的监督。这是我在上面做错事的线索,因为第二种方法可以使用 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 时。 (尝试注释掉不同的约束以查看是哪个导致了可怕的错误文本。)
最佳答案
错误信息是由于在添加约束的时候还没有创建self.superview
的关系造成的。
另一个错误随之而来,因为两个约束 thc 和 thc2 不能添加到 NSScrollView,它们需要添加到它的父 View 。
虽然以上仍然没有产生我想要的结果,但它消除了运行时出现的两个错误。
关于objective-c - 使用 AutoLayout 在哪里添加我想在 NSScrollView 中 float 的 subview ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27705146/