gpt4 book ai didi

swift 如何删除代码创建的按钮中的空白区域?

转载 作者:行者123 更新时间:2023-11-30 10:36:12 25 4
gpt4 key购买 nike

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

示例: enter image description here

        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.

关于swift 如何删除代码创建的按钮中的空白区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57969503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com