2015-09-17 93 views
-1

我正在重新使用一个Objective-C代码,其中有一个动态tableView,用于显示区域中的蓝牙设备。 我想在这个tableView的每一行添加一个按钮,它会触发一个动作并在屏幕底部显示一个内容。如何在动态表的每一行添加一个按钮?

当前代码和有趣的是

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]; 

    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"]; 
     cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    } 

    CLBeacon *beacon = (CLBeacon*)[self.beacons objectAtIndex:indexPath.row]; 
    NSString *proximityLabel = @""; 
    switch (beacon.proximity) { 
     case CLProximityFar: 
      proximityLabel = @"Far"; 
      break; 
     case CLProximityNear: 
      proximityLabel = @"Near"; 
      break; 
     case CLProximityImmediate: 
      proximityLabel = @"Immediate"; 
      break; 
     case CLProximityUnknown: 
      proximityLabel = @"Unknown"; 
      break; 
    } 

    cell.textLabel.text = proximityLabel; 

    NSString *detailLabel = [NSString stringWithFormat:@"Major: %d, Minor: %d, RSSI: %d, UUID: %@", 
          beacon.major.intValue, beacon.minor.intValue, (int)beacon.rssi, beacon.proximityUUID.UUIDString]; 
    cell.detailTextLabel.text = detailLabel; 

    return cell; 
} 

我想知道什么是做到这一点的最佳方式,并在插入这个代码的按钮。 我对Objective-C开发并不熟悉,并且寻找这个问题的所有示例/插图。

+0

有很多答案:http://stackoverflow.com/questions/7721364/add-buttons-programatically-to-table- view-cells –

+0

将'UIButton'添加到故事板中的原型单元格。将UIButton的'IBAction'添加到您的自定义单元格子类中。 –

+0

故事板中没有原型。这是一个TableView,每个找到的信标都显示在一个新行中。我希望每个按钮都可以调用一个函数并传递给它一个变量。 – phenetas

回答

0

您可以在细胞的初始化部分添加按钮,即

if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"]; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    // create your button and add it to your cell 
    UIButton *button = .... 
    [cell.contentView addSubview:button]; 
} 
+0

谢谢。我已经添加了按钮,现在我想知道如何在此按钮上设置操作。不知道该怎么做 – phenetas

相关问题