我正在我的TableView标题单元格中以编程方式创建一个按钮,并向其添加TouchUpInside Action。使用UIButton Header还包含另外两个UILabel。
问题:如果按钮被添加为SubView,则不响应。
但是当我从Method返回UIButton时它工作正常。
这是我的- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *viewHeader = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
viewHeader.tag = 101;
viewHeader.backgroundColor = [UIColor cyanColor];
UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnBack.frame = CGRectMake(15, 15, 50, 25);
//btnBack.titleLabel.text = @"Back";
[btnBack setTitle:@"Back" forState:UIControlStateNormal];
[btnBack addTarget:self action:@selector(Back:) forControlEvents:UIControlEventTouchUpInside];
btnBack.userInteractionEnabled = YES;
UILabel *lblPlayerName = [[UILabel alloc]initWithFrame:CGRectMake(75, 20, 60, 20)];
lblPlayerName.backgroundColor = [UIColor redColor];
UILabel *lblHighScoreOfPlayer = [[UILabel alloc]initWithFrame:CGRectMake(215, 20, 80, 20)];
lblHighScoreOfPlayer.backgroundColor = [UIColor yellowColor];
}
lblPlayerName.text = [@"Name" uppercaseString];
lblHighScoreOfPlayer.text = [@"Scores" uppercaseString];
[viewHeader addSubview:btnBack];
[viewHeader addSubview:lblPlayerName];
[viewHeader addSubview:lblHighScoreOfPlayer];
return viewHeader;
}
答案 0 :(得分:1)
首先,您将图像视图添加为用于标题视图的uiview的子视图,而不是
UIView *viewHeader = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
程序应按以下顺序进行。
step1.allocate UIView step2:添加imageView作为uiView的子视图 step3:添加按钮作为imageview的子视图 然后返回uiview
这是我测试的工作代码。
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnBack.frame = CGRectMake(15, 15, 50, 25);
[btnBack setTitle:@"Back" forState:UIControlStateNormal];
[btnBack addTarget:self action:@selector(Back:) forControlEvents:UIControlEventTouchUpInside];
btnBack.userInteractionEnabled = YES;
[headerView addSubview: btnBack];
return headerView;
}
答案 1 :(得分:0)
我不确定,但您可能应为主userInteractionEnabled
UIView
设置属性viewHeader.userInteractionEnabled = YES;
。
正如提及@ott尝试为UIView
分配UIImageView
而非viewHeader
:
UIView *viewHeader = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
试试吧。希望,它会帮助你