如何在UITableViewCell上添加按钮

时间:2013-06-26 09:19:23

标签: ios objective-c uitableview

我有一个预先填充的UITableViewCell,其中一个单元格有一个标签UITextField。假设我有一个带有标签“map”的单元格,我想在该单元格上添加按钮,我该怎么做呢? 我试过但这不起作用。
这是代码:

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

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    if (indexPath.row == 0)
    {
        ((UILabel*)[cell viewWithTag:100]).text = @"Title";
        ((UITextField*)[cell viewWithTag:101]).placeholder = @"Title";
        ((UITextField*)[cell viewWithTag:101]).text = arrayResourceColumns[indexPath.section][indexPath.row][@"resource_title"];
        ((UITextField*)[cell viewWithTag:101]).keyboardType = UIKeyboardTypeDefault;
    }
    else
    {
        if([arrayResourceColumns[indexPath.section][indexPath.row][@"label"] isEqualToString:@"OT ($)"]){

            NSInteger desiredLabel = (NSInteger)(arrayResourceColumns[indexPath.section][indexPath.row][@"label"]);

            //NSString *desiredLabel = arrayResourceColumns[indexPath.section][indexPath.row][@"label"];
            NSLog(@"Label is>>>>--------%ld", (long)desiredLabel);

            if (indexPath.row == desiredLabel ) {
                UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
                [b setFrame:CGRectMake(0, 0, 50, 50)];
            }


        }
        ((UILabel*)[cell viewWithTag:100]).text = arrayResourceColumns[indexPath.section][indexPath.row][@"label"];
        ((UITextField*)[cell viewWithTag:101]).placeholder = ((UILabel*)[cell viewWithTag:100]).text;
        ((UITextField*)[cell viewWithTag:101]).text = arrayResourceColumns[indexPath.section][indexPath.row][@"attribute_value"];

        if (indexPath.row == [arrayResourceColumns[indexPath.section] count] - 1)
        {
            ((UITextField*)[cell viewWithTag:101]).enabled = NO;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

有几种方法可以在UITAbleViewCell上添加按钮:
1)如果您使用的是故事板,您可以使用按钮创建单元格原型,然后您可以使用tag属性访问此按钮 2)子类UITableViewCell并在init上添加按钮 3)在tableView:cellForRowAtIndexPath:方法

中向单元格添加按钮

<强> UPD
Here is教程如何使用Storyboards自定义UITableViewCell