swift 如何删除代码创建的按钮中的空 space?

swift how to remove empty space in button created by code?

如何删除代码创建的按钮中的空space?尝试使用插图和约束但没有解决方案。

示例:

        let myButton = UIButton()
        myButton.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(myButton)
        myButton.backgroundColor = .lightGray
        myButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
        myButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        myButton.heightAnchor.constraint(equalToConstant: 50).isActive = true //this should be not hardcoded but flexible
        myButton.widthAnchor.constraint(equalToConstant: 200).isActive = true //this should be not hardcoded but flexible
        let downImage = UIImage(named: "caring")
        myButton.imageView?.backgroundColor = .green
        myButton.imageView?.contentMode = .scaleToFill
        myButton.setTitle("Medium Text", for: .normal)
        myButton.setImage(downImage, for: .normal)
        myButton.semanticContentAttribute = .forceRightToLeft
        myButton.imageEdgeInsets = .init(top: 0, left: 16, bottom: 0, right: 0)
//        myButton.imageView?.translatesAutoresizingMaskIntoConstraints = false
//        myButton.imageView?.widthAnchor.constraint(equalToConstant: 24).isActive = true
//        myButton.imageView?.heightAnchor.constraint(equalToConstant: 24).isActive = true
//        myButton.imageView?.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
//        myButton.imageView?.trailingAnchor.constraint(equalTo: myButton.trailingAnchor, constant: 0).isActive = true
//        myButton.contentEdgeInsets.right = 0
//        myButton.contentEdgeInsets.top = 0
//        myButton.contentEdgeInsets.bottom = 0
//
        myButton.titleEdgeInsets.left = 16
        myButton.titleEdgeInsets.right = 16

您可以使用以下步骤来实现此目的。

 //        step 1: Setup the button
    let myButton = UIButton()
    myButton.translatesAutoresizingMaskIntoConstraints = false
    myButton.backgroundColor = .lightGray
    myButton.setTitle("Medium Text", for: .normal)
    myButton.backgroundColor = .lightGray
//        step 2: Set the imageView Of the button
    let downImage = UIImage(named: "caring")
    myButton.imageView?.backgroundColor = .green
    myButton.imageView?.contentMode = .scaleToFill
    myButton.setImage(downImage, for: .normal)
    myButton.semanticContentAttribute = .forceRightToLeft
//        step 3: Here set up the button frames and add the button to the view
    myButton.sizeToFit()
    self.view.addSubview(myButton)
    myButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
    myButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

There is no need to set the height and the width anchor which you set in your code.