0

我目前正在尝试向我的应用程序添加一个按钮。如果用户按下它,它应该显示一个警报。

我想将按钮添加到 a 的部分标题tableview.这是我的代码tableView:viewForHeaderInSection:

UIImageView *headerView = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 20)] autorelease];
...
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(180, 4, 15, 15)];
UIImage *img=[UIImage imageNamed:@"myimg"];
[button setImage:img forState:UIControlStateNormal];
[button addTarget:self action:@selector(showMyAlert) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubview:button];
return headerView;

在同一个班级中,我有方法:

-(void)showMyAlert{
    NSLog(@"HERE SHOW ALERT");
    ...
}

该按钮已正确显示,showMyAlert但当我按下它时从未调用该方法。有谁知道我的代码有什么问题?谢谢,如果你能帮助我:)

4

4 回答 4

0

试试这个,在 viewDidLoad 中,

-(void)viewDidLoad
{
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
UIImageView *imageView = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 20)] autorelease];
[headerView addSubview:imageView];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(180, 4, 15, 15)];
UIImage *img=[UIImage imageNamed:@"myimg"];
[button setImage:img forState:UIControlStateNormal];
[button addTarget:self action:@selector(showMyAlert) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubview:button];
self.tableView.tableHeaderView = headerView;
}
于 2013-10-25T09:52:45.900 回答
0

确保 img 不为零。如果为 nil,您的按钮将没有图像,您将什么也看不到。

于 2013-10-25T09:41:44.223 回答
0

更改您的UIImageViewasUIView并将其作为标题视图返回。

UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 20)] autorelease];
于 2013-10-25T10:34:51.377 回答
0

修改下面的代码行,试试这样: -

[button addTarget:self action:@selector(showMyAlert:) forControlEvents:UIControlEventTouchUpInside];

-(IBAction)showMyAlert:(id)sender{
    NSLog(@"HERE SHOW ALERT");
    ...
}
于 2013-10-25T09:49:54.110 回答