FatalError
FatalError

Reputation: 574

How to create a custom UIButton in code and use it in a xib?

I have a class MyButton : UIButton which inherits from UIButton. I do a bunch of things in the initWithFrame (the only constructor)of MyButton say like setting the backgroundcolor.

Now I want to use this MyButton in my xib. so that I dont keep setting these properties again and again for all my buttons. I have also set the Custom Class to MyButton in the Identity Inspector for the button in the xib.

Nothing still reflects the properties I set in the xib. This could have been easily done if it was in the code.

My question is, 1) What gets called when you create button thru a xib (like you call initWithFrame when you programmatically create a button) ?

2) How do I get it to see the properties I set in the MyButton ? Is moving out of xib and doing it programatically the only way ?

thanks in advance !

Upvotes: 0

Views: 1641

Answers (2)

Sujith Thankachan
Sujith Thankachan

Reputation: 3506

You can simply set it in your xib file. For that:

  1. Select the button in the xib file.
  2. Click the Identity Inspector button.
  3. Type the name of your custom class(MyButton for your case) in the Class field.

Now your button will be with the Type MyButton class.

EDIT

Check Apple's documentation on Adding a Custom Object. This will give you more idea.

Upvotes: 0

Wayne Hartman
Wayne Hartman

Reputation: 18477

  1. Typically with initWithCoder:
  2. You can use the identity inspector in Interface Builder to set values using the keypath of the attributes. In this example, you can change the CALayer properties of the view:

enter image description here

Upvotes: 1

Related Questions