【发布时间】:2010-08-25 06:29:25
【问题描述】:
这让我发疯了...我看过一些关于类似问题的帖子,但似乎无法让它发挥作用,所以这里是:
这是一个非常简单的示例,我只是在自定义视图中创建自定义 UIButton,然后为其分配自定义操作以响应触摸事件。当我运行应用程序时,会创建按钮,但当我尝试单击它时没有任何反应。
这是我的自定义类的代码:
#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!");
}
这里是 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;
}
正如您从自定义类中看到的那样,从我在其他帖子中读到的内容中,我尝试添加一些内容以增加成功的机会:
- 启用自定义视图用户交互
- 将 UIButton 置于最前面
- 确保按钮的框架完全包含在视图的框架中
- ...
...但是还是不行!...
任何帮助将不胜感激 - 谢谢!
编辑:这里也是自定义视图的标题:
#import <UIKit/UIKit.h>
@interface MySegmentedControl : UIView {
UIButton *button1;
}
@property (nonatomic, retain) IBOutlet UIButton *button1;
- (void)action;
@end
【问题讨论】:
标签: iphone custom-controls uibutton