在UITableViewCell中动态分配UIButton事件

时间:2012-06-12 06:51:28

标签: iphone objective-c ios uitableview ios5

我创建了一个自定义的UITableViewCell子类,其中包含一个名为testbtn的按钮。然后我尝试将该按钮的事件分配给另一个类,但这对我不起作用。请你告诉我我哪里出错了?

这是我的代码:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"PatientCell";
    PatientCell *cell = (PatientCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
            NSArray *TopLevelOb = [[NSBundle mainBundle] loadNibNamed:@"PatientCell" owner:self options:nil];
            for (id currentlevelob in TopLevelOb) {
                if([currentlevelob isKindOfClass:[PatientCell class]]){
                    cell = (PatientCell *) currentlevelob;
                    cell.test.text = @"some text";
                    cell.HR.text =@"80";
                    cell.ABP.text =@"120/20";
                    cell.SOP2.text =@"95";
                    cell.RR.text=@"98";
                    [cell.testbtn addTarget:self action:@selector(openLiveData:)   
                       forControlEvents:UIControlEventTouchUpInside];// **this event is not fire to openLiveData method**
                    break;
                }
            }
        } else {
            NSArray *TopLevelOb = [[NSBundle mainBundle] loadNibNamed:@"PatientCell_iPad" owner:self options:nil];
            for (id currentlevelob in TopLevelOb) {
                if([currentlevelob isKindOfClass:[PatientCell class]]){
                    cell = (PatientCell *) currentlevelob;
                    cell.test.text = [nameArry objectAtIndex:indexPath.row];
                    cell.HR.text =@"80";
                    cell.ABP.text =@"120/20";
                    cell.SOP2.text =@"95";
                    cell.RR.text=@"98";
                    [cell.testbtn addTarget:self action:@selector(openLiveData:) forControlEvents:UIControlEventTouchUpInside]; 
                    break;
                }
            }     
        }
    }
    return cell;
}

-(IBAction)openLiveData:(id)sender{
     NSLog(@"hello ");
 }

3 个答案:

答案 0 :(得分:1)

检查您的按钮是否连接到NIB中的testBtn实例变量。

祝你好运

Ť

答案 1 :(得分:0)

这样做忘记指定控制事件:

  [cell.testbtn addTarget:self action:@selector(openLiveData:) forControlEvents:UIControlEventTouchUpInside];

希望有用

答案 2 :(得分:0)

它应该可以在iPhone版本中正常工作但在iPad版本中应该是问题,因为您在forControlEvents:UIControlStateNormal处提到了forControlEvents:UIControlEventTouchUpInside