开发者

Create Custom UIButton class

I was wondering the best way to do the following,

  1. Create many buttons.
  2. Allow each button to be ID'ed by a custom made string.

I read that maybe subclassing UIView might work, but that subclassing UIButton would be quite impossible. Also if I were to subclass UIView and then fill the frame with a button, would adding say 50 of these to the screen cause an开发者_JAVA技巧y performance issues, obviously graphics would have something to do with that. But might there be an easier way?

I found it pretty easy to subclass the UItableviewcell, and i would like just a quick tip or snip'it of code to tell me how to something similar to a UIButton.

Thanks!


The best way to do this is to use the tag property of UIView. (UIButton is a subclass of UIView.) A tag is just an integer, so it is very suitable for loops and such things. Needless to say, it works with subclasses also.

This method also shows up in many of Apple's examples. It is convenient because you do not need to keep any other variables around. Also, there are very practical methods to access the buttons via viewWithTag:

UIButton *button = (UIButton *)[theSuperView viewWithTag:i];

I have for example implemented a piano keyboard in this way. To write an algorithm that identifies each key (or pitch) with the tag is quite simple.


If you really want to subclass UIButton, then you can do it. However, you may run into problems if you make calls to +buttonWithType which instantiates subclasses instead of UIButton directly.

If all you want to is to add a custom NSString or other object to associate with each button, then you can use Associative References to do this.

You can create many buttons at once using a for loop, possibly with the aide of an NSArray to hold the buttons if you do not want to add them to a subview right away.

Another approach is to create an NSDictionary where the objects are UIButtons and the keys are the NSStrings by which you want to identify each button.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜