Reputation: 1052
I've created a custom button called TaskUIButton that inherits from UIButton. The only difference I have right now is a "va" property.
Here's the interface
// TaskUIButton.h
@interface TaskUIButton : UIButton
{
NSString *va;
}
@property(nonatomic, retain) NSString *va;
@end
And the implementation file
//TaskUIButton.m
@implementation TaskUIButton
@synthesize va;
@end
Now, I've got an action that I'm using which I want to use to set and retrieve the va property of a button (just for testing/experimentation of course).
Here is where the button action is
- (IBAction)setAndRetrieveVa:(id)sender{
TaskUIButton *imaButton = [TaskUIButton buttonWithType:UIButtonTypeRoundedRect];
imaButton.va = @"please work";
NSLog(@"%@", imaButton.va);
}
Upon activating the setAndRetrieveVa: action, my app crashes with:
-[UIRoundedRectButton setVa:]: unrecognized selector sent to instance 0x4b3a5a0
I'm sure that its a stupid mistake on my part, but I've been going at it for a while and would love some insight!
Thanks!
Upvotes: 0
Views: 962
Reputation: 1052
I ended up just extending UIControl...turned out to be alot easier :)
- (IBAction)setAndRetrieveVa:(id)sender{
TaskUIButton *newTaskButton = [[TaskUIButton alloc] initWithFrame:CGRectMake(29.0, (76.0+ (88*taskCounter)), 692, 80.0)];
[newTaskButton addTarget:self action:@selector(function1:)forControlEvents:UIControlEventTouchUpInside];
[newTaskButton addTarget:self action:@selector(function2:) forControlEvents:UIControlEventTouchDragExit];
[newTaskButton setBackgroundColor:[UIColor grayColor]];
[newTaskButton setTitle:@"0" forState:UIControlStateNormal];
[newTaskButton setVa:@"please work!"];
NSLog(@"%@", newTaskButton.va);
}
And for click highlighting, I can always add a function that changes the background color when touch-down occurs, and switches the color back when touch-up occurs. Hurrah!
Upvotes: 0
Reputation: 44633
You are getting this because buttonWithType:
is returning a new object which is a UIRoundedRectButton
object which is a subclass of UIButton
. You can't alter this behavior of the method unless you override but you are unlikely to get what you want. You should take the alloc-init
approach.
Using Associative References
You will need to #import <Foundation/NSObjCRuntime.h>
for this to work.
To set,
objc_setAssociatedObject(button, "va", @"This is the string", OBJC_ASSOCIATION_RETAIN);
And to retrieve,
NSString * va = (NSString *)objc_getAssociatedObject(button, "va");
This way you wouldn't need to subclass UIButton
.
Upvotes: 4