Center UIButton image with inset
Asked Answered
T

3

24

I'd like to create a UIButton, but with a larger tap area than the image. (Ex: 40x40 button, but the image is only 20x20, centered).

Is that what imageEdgeInsets is for?

I've set it both programatically: (This is in the UIView which contains my button)

- (void)awakeFromNib {
    [_plusButton setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    [_plusButton setContentMode:UIViewContentModeCenter];
}

And from storyboard

enter image description here

But neither of them seem to work.

Trichocyst answered 2/6, 2014 at 9:2 Comment(0)
L
20

Got it I think that you set your image as a background image of the button, set it as a image then it will never stretches(remains in it original shape) and imageEdgeInsets will works on it properly.

Like:

enter image description here

Lorianne answered 2/6, 2014 at 9:15 Comment(2)
You can try different insets settings using this simple app github.com/tomas789/UIButtonEdgeInsetsBeaumont
UGH, this took way too long for me to find. Thank you.Lunar
G
12

Swift 3 & 4 Solution programmatically.

buttonOutlet.setImage(UIImage(name: "iconWhite"), for: .normal)
buttonOutlet.imageEdgeInsets = UIEdgeInsets(top: 10, left:10, bottom: 10, right: 10)
Glomerulus answered 9/2, 2018 at 12:54 Comment(0)
I
9

Here is a simple example of how to use imageEdgeInsets This will make a 20x20 button with a hittable area 10 pixels bigger all the way around (40x40)

    var expandHittableAreaAmt: CGFloat = 10
    var buttonWidth: CGFloat = 20
    var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
    button.frame = CGRectMake(0, 0, 
        buttonWidth + expandHittableAreaAmt*2, 
        buttonWidth + expandHittableAreaAmt*2)
    button.imageEdgeInsets = UIEdgeInsetsMake(expandHittableAreaAmt, 
        expandHittableAreaAmt, expandHittableAreaAmt, expandHittableAreaAmt)
    button.setImage(UIImage(named: "buttonImage"), forState: .Normal) //20x20 image
    button.addTarget(self, action: "didTouchButton:", forControlEvents: .TouchUpInside)
Indus answered 10/11, 2014 at 20:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.