Calling IBAction Programmatically in TableViewHeader
I am creating a button pro-grammatically in my TableView Header cell and adding TouchUpInside Action to it. With UIButton Header contains two other UILabels also.
Problem : If Button Is added as SubView, Its not respondin.
But when I return only UIButton from Method It is working fine.
Here is my code of - (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;
}
First you add the image view as a subView of uiview for header view instead of
UIView *viewHeader = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
The procedure should be in the following order.
step1.allocate UIView step2:add imageView as the subView of uiView step3:add the button as the subview of imageview then return the uiview
This is a working code i tested.
- (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;
}
I'm not sure but probably you should set property userInteractionEnabled
for your main UIView
viewHeader.userInteractionEnabled = YES;
.
And as mentions @ott try to allocate UIView
not UIImageView
for viewHeader
:
UIView *viewHeader = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
Try it. Hope, it will help you
精彩评论