在 iOS 上,我以编程方式创建了一个按钮,但事件没有触发。
UIButton * anyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[anyButton addTarget:self action:@selector(handleAnyButton:) forControlEvents:UIControlEventTouchUpInside];
anyButton.frame = CGRectMake(150, 350, 22, 22);
[self addSubview:anyButton];
代码放置在自定义视图(不是自定义视图控制器)中,但我不能让它触发事件。没有显示新闻动画。自定义视图启用了 userInteractionEnabled。我还尝试使用情节提要在同一视图上创建另一个按钮,并且该按钮正在工作。按钮代码在 initWithFrame 中完成。一定是一些我没有发现的简单错误,我已经为此苦苦思索了好几个小时。
编辑:
事件处理程序:
-(void) handleAnyButton:(UIButton *)button
{
NSLog(@"handleAnybutton called");
}
EDIT2:上述按钮代码在 PKLocationsSelectionView 类的 [self setup] 中完成。
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self setup];
}
return self;
}
这个视图是在负责这个层次结构的视图控制器(PKLocSelectionViewController)中以编程方式创建的:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
CGFloat fieldsHeight = 88;
UIView * view = [[PKLocationsSelectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, fieldsHeight)];
[self.view addSubview:view];
}