开发者

UIButton simple subclass (need to have an NSString property like a tag)

开发者 https://www.devze.com 2023-02-20 16:34 出处:网络
I have a view that has a bunch of programmatically-created UIButton objects (rounded rectangle type), but I need to store a little bit of information in them, identifying each button. I was doing fine

I have a view that has a bunch of programmatically-created UIButton objects (rounded rectangle type), but I need to store a little bit of information in them, identifying each button. I was doing fine with the tag, but the numbers got too large, and I would like to basically have another piece of info associated with each button, this time an NSString. By the way, the label is taken, I can't use that. What's the simplest/quickest way to go about this? Do I need to subclass UIButton and add my own property to it like stringTag? I'm not super proficient in obj-c yet, and read somewhere this is a pain. Is there a simpler way to store an additional string in开发者_StackOverflow社区 my UIButtons? Thanks a lot in advance for any advice.


Subclassing uibutton is a real pain. They don't usually work as expected since UIButton is an abstract class. Therefore to make a fully working button you may have to override quite a few methods to get the button to do everything the the Apple subclasses do. Instead if you just need to add storage you can use associative references. you must #import <objc/runtime.h> to use the functions.

The best way to do this is to define a string constant NSString *const buttonTagName = @"com.youapp.buttonTag"; and store tags with this as the key objc_setAssociatedObject(button, buttonTagName, tagForCurrentButton, OBJC_ASSOCIATION_RETAIN); .


I think adding an NSString with some id info shouldn't mess up your UIButton subclass too much. At least it's easy to try it out, we are talking 10 lines of code here. I subclassed a UIButton and overrided initWithFrame method once and got it working correctly. But it's true, it is a pain and don't ask me why I did it :)

0

精彩评论

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