【问题标题】:UIButton is resized to fit UIImageUIButton 调整大小以适应 UIImage
【发布时间】:2019-01-31 15:27:24
【问题描述】:
    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 的图像资源吗?

【问题讨论】:

    标签: swift uibutton uiimage resize constraints


    【解决方案1】:

    试试这个。它告诉按钮它不应该拥抱它的内容,并根据它的其他约束展开:

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

    【讨论】:

    • 不,结果是一样的
    猜你喜欢
    • 2012-05-02
    • 1970-01-01
    • 2015-12-10
    • 2015-11-17
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    相关资源
    最近更新 更多