我正在尝试为我的应用添加一个按钮。如果用户按下它,它应该显示警告。
我想将按钮添加到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
方法。
有没有人知道我的代码有什么问题?
谢谢,如果你能帮助我:)。
答案 0 :(得分:0)
确保img不是零。如果为零,则按钮将没有图像,您将看不到任何内容。
答案 1 :(得分:0)
修改下面的代码行,试试这样: -
[button addTarget:self action:@selector(showMyAlert:) forControlEvents:UIControlEventTouchUpInside];
-(IBAction)showMyAlert:(id)sender{
NSLog(@"HERE SHOW ALERT");
...
}
答案 2 :(得分: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;
}
答案 3 :(得分:0)
将UIImageView
更改为UIView
并将其作为标题视图返回。
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 20)] autorelease];