简体   繁体   English

在 Swift 的对话框中以编程方式更改 UIButton 大小

[英]Change UIButton size programmatically in dialog in Swift

I create dialog with custom button UIButton in swift IOS. How can change UIButton size programmatically.我在 swift IOS 中使用自定义按钮 UIButton 创建对话框。如何以编程方式更改 UIButton 大小。

class SuccessMessageView: UIView, UITextFieldDelegate {

private var buttonConfirm : UIButton = {
    
    let button = UIButton()
    button.setTitle("Ok", for: .normal)
    button.backgroundColor = UIColor(rgb: PreferenceManager.shared.hasDevice() ? purpleColour : orangeColour)
    button.setTitleColor(.white, for: .normal)
    button.layer.cornerRadius = 10
    button.addTarget(self, action: #selector(confirmFunc), for: .touchDown)
    
    button.translatesAutoresizingMaskIntoConstraints = false
    button.widthAnchor.constraint(equalToConstant: 140.0).isActive = true
    button.frame.size.width = 140
    return button
}
}

Could you try this?你能试试这个吗? Just remove the frame-related lines.只需删除与框架相关的行。

private lazy var buttonConfirm : UIButton = {
    let button = UIButton()
    button.setTitle("Ok", for: .normal)
    button.backgroundColor = .red
    button.setTitleColor(.white, for: .normal)
    button.layer.cornerRadius = 10
    button.addTarget(self, action: #selector(confirmFunc), for: .touchUpInside)

    button.translatesAutoresizingMaskIntoConstraints = false
    button.widthAnchor.constraint(equalToConstant: 200.0).isActive = true
    button.heightAnchor.constraint(equalToConstant: 48).isActive = true
    return button
}()
 fileprivate func Frame() -> CGRect {
        var circleFrame = CGRect(x: 0, y: 0, width: 2, height: 2)
        return circleFrame
    }

I found the solution for set UIButton width and height programatically like that set with constant.我以编程方式找到了设置 UIButton 宽度和高度的解决方案,就像使用常量设置一样。

button.anchor(nil, left: nil, bottom: nil, right: nil, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 20, heightConstant: 30)
    button.anchorCenterXToSuperview()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM