gpt4 book ai didi

ios - 用户界面按钮 : superimpose a title on top of an image programmatically

转载 作者:行者123 更新时间:2023-11-30 12:13:42 24 4
gpt4 key购买 nike

如何以编程方式将按钮标题叠加在按钮图像顶部,并将它们放置在彼此重叠的按钮框架的正中心?

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 作为按钮标题并将其添加为按钮的 subview ?

谢谢!

最佳答案

您可以使用图像插图来完成此操作,但我喜欢使用此类扩展 - 这样我就可以在应用程序中的任何位置使用它们,而无需子类化。这是我在 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)

关于ios - 用户界面按钮 : superimpose a title on top of an image programmatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45698733/

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