我正在尝试将两个视图添加到CallOutViewpushButton应位于底部,静态高度为20。然后,topView将填充其余部分。我试过使用SnapKit以编程方式执行此操作。但是这个按钮好像什么都填满了?我做错什么了?

       callOutView = UIView(frame: CGRectMake(-70+(self.frame.width/2), -65, 140, 60))
        callOutView!.backgroundColor = UIColor.clearColor()
        callOutView?.clipsToBounds = true
        callOutView?.layer.cornerRadius = 6
        self.addSubview(callOutView!)

        let topView = UIView()
        topView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.8)
        callOutView?.addSubview(topView)


        let pushButton = UIButton()
        pushButton.backgroundColor = UIColor(rgba: "#09316e").colorWithAlphaComponent(0.8)
        pushButton.setTitle("Se Mere", forState: UIControlState.Normal)
        pushButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        pushButton.titleLabel?.font = UIFont.systemFontOfSize(8)
        callOutView?.addSubview(pushButton)

        topView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(callOutView!).offset(0)
            make.left.equalTo(callOutView!).offset(0)
            make.bottom.equalTo(pushButton).offset(0)
            make.right.equalTo(callOutView!).offset(0)
            make.height.equalTo(40)

        }

        pushButton.snp_makeConstraints { (make) -> Void in
            make.height.equalTo(20)
            make.top.equalTo(topView).offset(0)
            make.left.equalTo(callOutView!).offset(0)
            make.bottom.equalTo(0).offset(0)
            make.right.equalTo(callOutView!).offset(0)

        }

最佳答案

问题是,存在一些相互冲突的约束,这将使自动布局系统打破其中的一些约束。

topView.snp_makeConstraints { (make) -> Void in
    ...
    make.bottom.equalTo(pushButton).offset(0)
    ...
}


pushButton.snp_makeConstraints { (make) -> Void in
    ...
    make.top.equalTo(topView).offset(0)
    ...
}

上面的两个约束告诉自动布局系统:
放置topViewpushButton并对齐上边缘。
放置topViewpushButton,使底边对齐。
这是不可能的,如果你给topViewpushButton不同的高度。
而且,这显然不是你想要的。你想要的是“把pushButton放在topView下面”。
下面是修改后的代码,使pushButton位于topView的正下方:
topView.snp_makeConstraints { (make) -> Void in
    ...
    make.bottom.equalTo(pushButton.snp_top).offset(0)
    ...
}


pushButton.snp_makeConstraints { (make) -> Void in
    ...
    make.top.equalTo(topView.snp_bottom).offset(0)
    ...
}

07-27 13:40