简体   繁体   中英

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 any 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 UIButton s and the keys are the NSString s by which you want to identify each button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM