2015-09-17 91 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

相關問題