调整UIButton的大小以适合UIImage

时间:2019-01-31 15:27:24

标签: swift uibutton uiimage resize constraints

    let btn = UIButton(frame: CGRect.zero)
    btn.setImage(..., for: UIControlState.normal)
    addSubview(btn)
    btn.translatesAutoresizingMaskIntoConstraints = false
    btn.rightAnchor.constraint(equalTo: btn.superview!.rightAnchor, constant: -32).isActive = true
    btn.topAnchor.constraint(equalTo: btn.superview!.topAnchor, constant: 6 + vc.view.safeAreaInsets.top).isActive = true
    btn.widthAnchor.constraint(equalToConstant: 32)
    btn.heightAnchor.constraint(equalToConstant: 32)

    btn.backgroundColor = .black //to check the rect

图像尺寸为16x16。该按钮应至少增大两倍(因为触摸区域较小)。

但是当我运行该应用程序时,该按钮变为16x22(22-高度)。在“调试视图层次结构”中,我还看到其约束变为width==16height==22。 在同一时间,距离约束正常工作。

那我的错误是什么?还是我必须使用适合按钮1:1的图像资源?

1 个答案:

答案 0 :(得分:0)

尝试一下。它告诉按钮,它不应该拥抱它的内容,和扩散根据其其他约束出:

btn.setContentHuggingPriority(.defaultLow, for: .horizontal)
btn.setContentHuggingPriority(.defaultLow, for: .vertical)