2

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?

Thomas
  • 2,356
  • 7
  • 23
  • 59
  • hm ... i suggest you to do the Photoshop job again to make the picture large enough. – user3441734 Dec 27 '15 at 10:22
  • The easiest way is to make the the image larger, or embed the button inside of a clear UIView and add a tap gesture recognizer to it which triggers the optionsButtonPressed action. – Julian J. Tejera Dec 27 '15 at 14:37

3 Answers3

5

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)

Jordan H
  • 52,571
  • 37
  • 201
  • 351
1

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

Community
  • 1
  • 1
Ethan Halprin
  • 470
  • 3
  • 11
0
optionsButton.setImage(UIImage(named: "CalendarEventArrowIcon"), forState: UIControlState.Normal)

optionsButton.addTarget(self, action: Selector("optionsButtonPressed"), forControlEvents: UIControlEvents.TouchDown)
pradip kikani
  • 627
  • 6
  • 14
  • all you did was take my code and add the `Selector` tag to the action parameter. Swift 2 doesn't need the `Selector` tag so this does nothing – Thomas Dec 27 '15 at 09:20