简体   繁体   English

UIButton:以编程方式在图像上方叠加标题

[英]UIButton: superimpose a title on top of an image programmatically

How do I superimpose a button title on top of a button image programmatically and position them both to be dead center in the button frame overlapping each other? 如何以编程方式将按钮标题叠加在按钮图像的上方,并将它们放置在彼此重叠的按钮框架中的死点处?

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

Do I have to set the image as a background image? 我必须将图像设置为背景图像吗? Do I need to create a UILabel as the button title and add it as a subview of the button? 我是否需要创建UILabel作为按钮标题并将其添加为按钮的子视图?

Thanks! 谢谢!

You could try: 您可以尝试:

    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

You can do this with image insets, but I like to use extensions for things like this - that way I can use them anywhere in my app without subclassing. 您可以使用图像插图进行此操作,但是我喜欢对此类事情使用扩展名-这样,我可以在应用程序中的任何位置使用它们而无需子类化。 Here's my code for setting an image position in a UIButton: 这是我在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
}

Then I call it as follows 然后我称它为

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

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

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