UIButton:以编程方式将标题叠加在图像顶部



如何以编程方式将按钮标题叠加在按钮图像的顶部,并将它们定位为按钮帧中相互重叠的死点?

let button = UIButton()
button.setImage(coolpic, for .normal)
button.contentMode = .center
button.setTitle("tap me", for: .normal)
// a bunch of constraints and styling that define the frame

我必须将图像设置为背景图像吗?我是否需要创建一个 UILabel 作为按钮标题并将其添加为按钮的子视图?

谢谢!

您可以使用图像插图来执行此操作,但我喜欢将扩展用于此类内容 - 这样我就可以在应用程序中的任何位置使用它们而无需子类化。这是我在UIButton中设置图像位置的代码:

extension UIButton {
func setImagePosition(at pos:ButtonImagePosition, withAdjustment adj:CGFloat?) {
let _adj:CGFloat = (adj != nil) ? adj! : 0
let width = frame.size.width
var imgWidth = self.imageView?.frame.size.width 
switch pos {
case .center: 
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
case .right: 
imgWidth = imgWidth! - _adj
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: width - imgWidth!, bottom: 0, right: 0)
case .left: 
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: width + imgWidth!)
}
}
}
enum ButtonImagePosition {
case left
case right
case center
}

那我按如下方式称呼它

button.setImagePosition(at: .right, withAdjustment: nil)

你可以试试:

let button = UIButton()
button.setImage(UIImage(named:"yourImage.png")?, for: .normal)
button.setTitle("MyTitle", for: .normal)
button.titleLabel?.font = button.titleLabel?.font.withSize(15)
button.titleLabel?.textAlignment = .center

最新更新