0

I have a UIButton subclass that I initialize as:

MyButton *button = [MyButton buttonWithType:UIButtonTypeCustom];

I want to set the background color of this button.

If I do the following in the view controller after creating the button:

MyButton.backgroundColor = [UIColor ...];

It works fine. But if I try to do the following within the UIButton subclass, either in initWithFrame or in DrawRect:

self.backgroundColor = [UIColor ...];

It simply does nothing. The button remains transparent.

The thing is, my logic is such that I really need to set the color inside the UIButton subclass, not in the calling code.

Any ideas?

Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76
Amiram Stark
  • 2,208
  • 22
  • 32

2 Answers2

1

UIButton is not meant to be subclassed. It is a class cluster and you almost certainly get it wrong (it may break now or in the future). The base method buttonWithType: also will never return an instance of your class, so you need to go to great lengths to make all your code work.

The much better way is to to make a factory method that uses UIButton.buttonWithType: and configures the button the way you need it.

Eiko
  • 25,601
  • 15
  • 56
  • 71
  • How can we know that? Is there any apple ressource that explans which UI elements can be subclassed and which not? – berliner Feb 25 '14 at 10:56
  • Because there is no real documented init method on UIButton. We do need to call init, though. The most important properties is the buttonType, which is readonly - i.e. it must be set during creation. The behavior of the button depends heavily on it. The only way to set it, is to instantiate a new button by using the factory method '+buttonWithType:'. You are not guaranteed to get a working button - UIButton might be a somewhat abstract class, and there is no way to find out. Subclassing obviously works at the moment (as a "custom" button) just fine, but it *might* break in a heartbeat. – Eiko Feb 26 '14 at 19:46
0

Can you implement "Buttonwithtype" method in your subclass and write code there self.backgroundColor = [UIColor WhateverColor];

It should work. let me know.

Deeps
  • 4,399
  • 1
  • 26
  • 27
  • Yes it worked, thank you. (I couldn't implement just buttonWithType because I needed the color - using a property would be too late - so I implemented buttonWithType: andBackgroundColor: and called [super buttonWithType]. I'm still wondering what's wrong with the straightforward solution. – Amiram Stark Jun 27 '11 at 10:38
  • Great. May be it is because which ever method you wrote that doesn't call ? If this help then can you please mark it as answer? I am new to stackoverflow so I get some credits:) Thanks – Deeps Jun 27 '11 at 14:48