UIButton 图像即使有约束也会自动调整大小

UIButton image automatically resizes even with constraints

我有一个小问题,我可能无法理解。我以编程方式添加了一个 uibutton。我向那个按钮添加了一个 UIImage。我只是添加基本约束,但出于某种原因,它往往会在屏幕上显示 运行 时缩小到较小的尺寸。

以下是我生成按钮的代码:

var shareButton: UIButton!

    func addShareButton() {
        shareButton = UIButton()
        shareButton.autoresizesSubviews = false
        shareButton.clipsToBounds = true
        shareButton.translatesAutoresizingMaskIntoConstraints = false
        shareButton.adjustsImageWhenHighlighted = false
        shareButton.setImage(UIImage(named: "wshare"), for: .normal)
        shareButton.addTarget(self, action: #selector(shareButtonPressed), for: .touchDown)
        shareButton.addTarget(self, action: #selector(shareButtonReleased), for: .touchUpInside)
        view.addSubview(shareButton)
    }

    func addConstraints() {
        NSLayoutConstraint.activate([
            // Share Button
            shareButton.widthAnchor.constraint(equalToConstant: 60),
            shareButton.heightAnchor.constraint(equalToConstant: 60),
            shareButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -15),
            shareButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -25),
            ])
    }

    override func updateViewConstraints() {
        addConstraints()
        super.updateViewConstraints()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        addShareButton()
    }

它生成的是这样的:

更大的盒子应该是实际尺寸 60x60,但它神奇地缩小到 32x32。

你能帮我指出问题吗?我知道我错过了一些很愚蠢的东西,但我无法理解它。

就个人而言,我喜欢将我的对象分开。虽然 UIButton 有一个 setImage(:UIImage) 方法,但我更喜欢创建一个 UIButton 然后添加我自己的 UIImageView 然后添加我自己的 UIImage。所以,在层次结构中

-- UIButton
    -- UIImageView
        -- UIImage

有了这个,您可以指定特定的边界和任何其他与 UIImageView 相关的变量。我发现这种方法非常具体,尤其是当您必须更改 UIImageView.