【问题标题】:'Cannot Install Constraint', reason: 'No common superview between views'无法安装约束',原因:'视图之间没有共同的超级视图
【发布时间】:2016-07-15 06:16:12
【问题描述】:
import UIKit
import SnapKit

class RecordButton: UIView {
     let box = UIView()
     let container = UIView()

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

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

    func setup() {
         container.snp_makeConstraints { (make) -> Void in
         make.width.equalTo(200)
         make.height.equalTo(200)
         make.center.equalTo(self.container)
         }
    box.snp_makeConstraints { (make) -> Void in
        make.top.equalTo(container).offset(50)
        make.left.equalTo(container).offset(50)
        make.bottom.equalTo(container).offset(-50)
        make.right.equalTo(container).offset(-50)
        make.center.equalTo(container)
    }
    self.addSubview(container)
    container.addSubview(box)
    setColor()

    }
    func setColor() {
         self.container.backgroundColor = UIColor.blackColor()
         self.box.backgroundColor = UIColor.orangeColor()
    }

}

为什么会显示这个错误?还有其他方法可以执行此操作吗?有什么建议吗? center.equalTo 创建此错误。我是 swift 新手,正在尝试实现 SnapKit 框架

【问题讨论】:

  • 在对视图安装约束之前尝试添加视图(在添加视图后将 sip_makeConstraints 块移至)

标签: ios swift snapkit


【解决方案1】:

这意味着您的视图或任何控制器都应该在公共视图中。 例如,视图 A 有两个按钮,分别是 X 和 Y,视图 B 有两个按钮 P 和 K,那么您可以将 P 和 K 的约束设置为相对于它的超级视图 B,而不是相对于视图 A。

如果有多个超级视图,请确保您对每个超级视图都给予了适当的约束。那么只有端点视图的约束才会得到满足。

日期:

首先在容器中添加盒子并在其父视图中添加容器,然后设置约束。并确保您在self.containercontainer 中分别获得container viewbox view 的中心。如果你设置top,bottom,leading and trailing,那么也不需要设置中心!

希望这会有所帮助:)

【讨论】:

  • 我知道我很傻,但你能就我的代码解释一下吗?那太好了。
  • 知道了!非常感谢:)
猜你喜欢
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-30
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多