Another Dude
Another Dude

Reputation: 1451

Create a custom UIButton with text and icon

I would like to create a custom UIButton looking like this:

enter image description here

The idea is simple, I want the titleLabel to start 24px from the leading, and stop 12px or more to the icon image (which is the square view at the right of the button). It can contain up to 2 lines.

The thing is that I have no idea where I should put this code in a class inheriting from UIButton.

What should go into draw(_ rect: CGRect)?

Also, should I use the titleLabel and titleEdgeInsets UIButton properties and the imageView/imageEdgeInsets as well, or instead use custom properties for this?

Upvotes: 0

Views: 482

Answers (1)

Asol
Asol

Reputation: 359

You just want these buttons to work, be tapped, and react somehow? These buttons are custom buttons, and you may a create a Cocoa Touch Class file for them; name it and let it inherit from and be a subclass of UIButton.

Then connect that file to your buttons in the storyboard. But first, you need to set/attach the newly created file to your buttons. Click on the button, In the identity inspector of your storyboard, with your button selected go to the Class field and type the name of your new file and don't forget to tap 'return' to save your changes.

Now, your buttons are attached to that custom UIButton class. From now, you can attach all your icon images and many more as outlets to your custom UIButton Class you just created.

Most importantly, now these buttons can be used on their own; they can be outlets or trigger action methods. And to make it look just as you except, you just have to initialize your buttons, i.e. provide an icon image, text, etc.

Is what I wrote clear? If not, I am glad to help you.

Upvotes: 3

Related Questions