0

I have a nib in that I added a button and given background image to it.
I created a sub class of UIButton and given that class to that button.

I want to override
- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state
for nib.
Is any way to do it?.

Thanks

Puneet Sharma
  • 9,369
  • 1
  • 27
  • 33
Sachin
  • 333
  • 1
  • 4
  • 19
  • 1
    Do it in your custom UIButton class. Whats the issue? – Puneet Sharma Aug 14 '13 at 08:03
  • Puneet is correct - it should work (if you set the class of the button correctly inside your NIB). Depending on what you want to do in your subclasses method you might still want to call `[super setBackgroundImage:forState:]` inside it. Othervwise you have to do everything it does on your own. – Rok Jarc Aug 14 '13 at 08:23
  • in my subclass setBackgroundImage:forState is not getting called – Sachin Aug 14 '13 at 08:39

2 Answers2

2

You CAN subclass a UIButton, but you should be careful on what you are doing. Just subclass it to change its behavior and not its appearance. To modify a UIButton appearance you should use the interface methods provided for that, such as:

setTitle:forState: 
setBackgroundImage:forState: 
setImage:forState:

UPDATED:

-(void)changeBackground:(UIImage *)image forState:(UIControlState)state
{
   [self setBackgroundImage:image forState:state];
}
Krishna Kumar
  • 1,652
  • 9
  • 17
  • but if i am setting background image in nib. and setBackgroundImage:forState: function is not getting called in my uibutton sub class – Sachin Aug 14 '13 at 08:33
  • Krishna i tell u my requirement, i need to support for IOS7 also. suppose one button is there. it has differ image for IOS7 and IOS6. so i want to write generic class for that. if i do as u told then i have to call this method from my code and i dont want that. i want if somebody put image name in nib. we can listen it in subclass and add postfix to image name if its ios7. – Sachin Aug 14 '13 at 08:45
  • then you can create two nib and init your customButton with nib name. Save your nib for ios7 and ios6 with your required image.. load it while initializing. Or call the updated method with your iOS version check... – Krishna Kumar Aug 14 '13 at 08:56
2

If you set background image of your button via GUI of Xcode, it will call the default method instead of your custom setBackgroundImage method.

In order to call your own method, you should call it explicitly after the view is loaded.

Mert Buran
  • 2,989
  • 2
  • 22
  • 34
  • 1
    Maybe you can do it with Objective-C categories, but I haven't used categories before, so all I can say is just give it a try. – Mert Buran Aug 14 '13 at 10:51