Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 532
James Dunay Avatar asked May 02 '26 14:05

James Dunay


1 Answers

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.

like image 166
Mundi Avatar answered May 05 '26 04:05

Mundi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!