Thomas
Thomas

Reputation: 2386

Swift setting image as button, clicking too hard

I've set a transparent image as the background for a UIButton I'm using. It looks perfect, but the problem is the transparent image is fairly small, so it's not easy for users to click it correctly on their first try.


Here's my code:

optionsButton.setBackgroundImage(UIImage(named: "CalendarEventArrowIcon"), forState: UIControlState.Normal)
optionsButton.addTarget(self, action: "optionsButtonPressed", forControlEvents: UIControlEvents.TouchDown)

Is there a way that I can take the current image I'm using, and place it inside a UIImage with a larger frame, and then make that the background image for the button programmatically in Swift?

By doing this, it would make it easier for a user to click the button since the background image would take up a larger area.

Or is the only way for me to actually to do something like this to go back into Photoshop and make the background image I'm using larger and no longer have a transparent background?

Upvotes: 2

Views: 1672

Answers (3)

Jordan H
Jordan H

Reputation: 55705

You can extend the tappable area of the button using contentEdgeInsets. For example, to add 15 points of padding around the button on all sides, add the following:

optionsButton.contentEdgeInsets = UIEdgeInsetsMake(15, 15, 15, 15)

Upvotes: 5

Ethan Halprin
Ethan Halprin

Reputation: 550

So bottom line you want to resize image programmatically in swift. See if this helps (votes 12 and comments say it works) :

swift resize image

Upvotes: 1

pradip kikani
pradip kikani

Reputation: 637

optionsButton.setImage(UIImage(named: "CalendarEventArrowIcon"), forState: UIControlState.Normal)

optionsButton.addTarget(self, action: Selector("optionsButtonPressed"), forControlEvents: UIControlEvents.TouchDown)

Upvotes: 0

Related Questions