This is driving me nuts... I've seen a few posts on similar issues but can't seem to make it work, so here it is:
it is a very simple example, I am just creating a custom UIButton in a custom view, then assigning it a custom action to respond to touch events. When I run the app, the button is created, but nothing happens when I try to click it.
Here is the code for my custom class:
#import "MySegmentedControl.h"
@implementation MySegmentedControl
@synthesize button1;
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
CGFloat a = frame.origin.x+5;
CGFloat b = frame.origin.y+5;
CGFloat l = frame.size.width-15;
CGFloat h = frame.size.height-15;
CGFloat c = a+l;
CGFloat d = b;
CGRect frame2 = CGRectMake(a, b, l, h);
UIButton *mybutton1 = [UIButton buttonWithType:UIButtonTypeCustom];
mybutton1.frame = frame2;
[mybutton1 setTitle:@"TEST" forState:UIControlStateNormal];
mybutton1.titleLabel.textColor = [UIColor blackColor];
mybutton1.backgroundColor = [UIColor blueColor];
[mybutton1 addTarget:self action:@selector(action)forControlEvents:UIControlEventTouchUpInside];
[self setButton1:mybutton1];
self.userInteractionEnabled = YES;
button1.userInteractionEnabled = YES;
[self addSubview:button1];
[self bringSubviewToFront:button1];
}
return self;
}
-(void)action {
[button1 setTitle:@"done" forState:UIControlStateNormal];
button1.backgroundColor = [UIColor greenColor];
NSLog(@"Working!");
}
And here is the appDelegate:
#import "MySegmentedControlAppDelegate.h"
#import "MySegmentedControl.h"
@implementation MySegmentedControlAppDelegate
@synthesize window;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[window makeKeyAndVisible];
MySegmentedControl *mycontrol = [[MySegmentedControl alloc] initWithFrame:CGRectMake(10,50,135,50)];
[window addSubview:mycontrol];
return YES;
}
as you can see from the custom class, from what I've read in other posts I've tried to add a few things to increase my chances of success:
- enabling the custom's view userinteraction
- bringing the UIButton to front
- making sure the button's frame is completely included in the view's frame
- ...
... yet it still doesn't work!...
Any help would be greatly appreciated - thanks!
Edit: here is also the header for the custom view:
#import <UIKit/UIKit.h>
@interface MySegmentedControl : UIView {
UIButton *button1;
}
@property (nonatomic, retain) IBOutlet UIButton *button1;
- (void)action;
@end