自定义TableView问题

时间:2012-03-20 06:51:27

标签: iphone ios uitableview

我的iphone应用中有自定义标题视图。它有一个自定义按钮。 但是自定义按钮操作不会触发,但会触发自定义类中的标题点击事件。请帮助我。如何在标题视图中触发按钮上的操作。

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSNumber *num=[NSNumber numberWithInt:section];
    UIView * customView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,320,50)]autorelease];
    customView.tag = section;
    [customView setUserInteractionEnabled:YES];
    customView.backgroundColor = [UIColor blackColor];

    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(260, 7, 25, 25);
    button.tag=section;
    [button addTarget:self action:@selector(expandCollapsing:) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:[UIImage imageNamed:@"add.png"] forState:UIControlEventTouchUpInside];
    [button setSelected:YES];

}

2 个答案:

答案 0 :(得分:0)

您可以实现自己的回调方法来执行此操作。

我做的是我在自定义视图中添加了TapGesture。当事件被触发时,我使用了一个回调方法将控件传递给我的tableView实现的viewController

您可以做什么加载标题时,您可以将标记值分配给customView

customHeader.tag = 1;

您可以在viewController中实现回调方法。

在CustomheaderView

 UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(checkBoxEventHandler:)];
  [recognizer setNumberOfTapsRequired:1];
  [recognizer setNumberOfTouchesRequired:1];
  [self setGestureRecognizers:[NSArray arrayWithObject:recognizer]];


-(IBAction)checkBoxEventHandler:(id)sender
{
     if ([self.delegate respondsToSelector:@selector(selectedHeader: atIndex:)]) 
     {
            [self.delegate selectedHeader:self atIndex:self.tag];
     }
}

In your viewController.m
-(void)selectedHeader:(myCustomHeader *)header atIndex:(int)index
{
   //header -> will give you the same instance you created in your viewController while loading this custom header view
   // So you can check the tag like this
   if(header.tag == 1) 
   { 
      //Do Stuff here
   }

   // index -> we are passing headerViews tag as index ie header.tag is equal to index
   // So checking the tag like this is the proper way
   if(index == 1) 
   { 
      //Do Stuff here
   }
}

答案 1 :(得分:0)

只需粘贴此代码即可解决您的问题:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{   
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(50.0, 0.0, 25, 25);
    [button setImage:[UIImage imageNamed:@"add.png"] forState:UIControlStateNormal];
    button.tag=section;
    [button addTarget:self action:@selector(expandCollapsing:) forControlEvents:UIControlEventTouchUpInside];
    [button setSelected:YES];
    return button;

}
-(void)expandCollapsing:(id)sender {
    UIButton *btn=(UIButton*)sender;
    NSLog(@"Tag:%d",[btn tag]);
}