heightAnchor.constraint不起作用(使用Swift的Apple FoodTracker教程)

Tho*_*AKI 9 constraints ios swift

我一直在做Apple的iOS教程; 开始开发iOS应用程序. https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/ImplementingACustomControl.html#//apple_ref/doc/uid/TP40015214-CH19-SW1

在本教程中,我在水平堆栈视图上添加了一个大小约束为44.0x44.0的按钮.但是,模拟器显示一个更大的按钮.

看起来大小限制不起作用.

我的代码如下.你能提出建议吗?

class RatingControl: UIStackView {
    //MARK: Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupButtons()
    }
    required init(coder: NSCoder) {
        super.init(coder: coder)
        setupButtons()
    }

    //MARK: Private Methods
    private func setupButtons() {
        let button = UIButton()
        button.backgroundColor = UIColor.red
        // Add constraints
        button.translatesAutoresizingMaskIntoConstraints = false
        button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
        button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true
        addArrangedSubview(button)
    }
}
Run Code Online (Sandbox Code Playgroud)

通过更改StackView的属性来解决此问题.

小智 16

我遇到过同样的问题.这是因为我没有将新的Horizo​​ntal StackView拖动到现有的Vertical StackView中.相反,我将它拖入主视图.如果查看Document Outline,新的StackView应该是第一个Vertical StackView的子项,并且位于Photo Image View下面.

这是在说明书中,但我不清楚.