LJulz
LJulz

Reputation: 123

UIButton with title and image

I need a button with an image inside of it and a text under the button. I can't use the image as a background because it would stretch the image. So my problem is if I use an image for the button, the title will be covered by the image. Is there any solution for this?

Here is an example how it should look like at the end:

enter image description here

Upvotes: 0

Views: 1773

Answers (5)

sheko
sheko

Reputation: 556

Change Title and Image Insets

enter image description here

also change control Vertical to bottom

enter image description here

Upvotes: 1

orkoden
orkoden

Reputation: 20006

You can adjust the following properties of UIButton: var titleEdgeInsets: UIEdgeInsets, var imageEdgeInsets: UIEdgeInsets.

Another way of doing this is subclassing UIControl. It's a UIView subclass that is meant to be used for such cases. UIButton is a subclass of UIControl for example. That way you have more control over the layout and you don't need to fight UIButton's builtin behaviour.

You can do your layout either in code or with Interface Builder in a xib file.

class MyButton: UIControl {

    var imageView: UIImageView
    var label: UILabel

    // adjust colors for changed states like highlighting, etc.
    override var isHighlighted: Bool {
        didSet { 
            if isHighlighted {
                backgroundColor = UIColor.grey              
            } else {
                backgroundColor = UIColor.white             
            }
        }
    }

    override var isSelected: Bool { didSet { ... } }    
    override var isEnabled: Bool { didSet { ... } }

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    override init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        imageView = UIImageView(image: UIImage(...))
        addSubView(imageView)
        label = UILabel(frame: CGRect(...))     
        addSubView(label)
        // TODO: add constraints for layout
    }
}

Upvotes: 0

Aleksandr Savchenko
Aleksandr Savchenko

Reputation: 61

You can subclass UIButton and redefine layoutSubviews method.

Upvotes: 0

Prashant Tukadiya
Prashant Tukadiya

Reputation: 16456

You have two options

1) Create UIView add Image , label and button

2) You can to set Title And Image inset , You can do it in XIB easily

For option two I have added simple example , (Replace it with your value)

enter image description here

enter image description here

Upvotes: 1

IvanMih
IvanMih

Reputation: 1864

You could make a separate UIImage and UILabel at the positions you prefer, and cover them with transparent UIButton. That should do the trick.

Hope it helps.

Upvotes: 0

Related Questions