添加按钮到UITableViewCell

时间:2012-01-12 14:20:10

标签: iphone objective-c uitableview uibutton

我想在UITableViewCell中添加一个按钮。这是我的代码:`

if (indexPath.row==2) {
    UIButton *scanQRCodeButton = [[UIButton alloc]init];

    scanQRCodeButton.frame = CGRectMake(0.0f, 5.0f, 320.0f, 44.0f);
    scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    scanQRCodeButton.backgroundColor = [UIColor redColor];
    [scanQRCodeButton setTitle:@"Hello" forState:UIControlStateNormal];

    [cell addSubview:scanQRCodeButton];
}`

现在,当我运行应用程序时,我只看到一个空行!有什么想法吗?

5 个答案:

答案 0 :(得分:13)

虽然把它放在单元格的contentView中是很自然的,但我很确定这不是问题(实际上,在过去,我从来没有在contentView中正确显示子视图,所以我总是使用了细胞)。

无论如何,问题涉及开始创建按钮时的前三行。前两行很好,但代码停止使用:

scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

buttonWithType:实际上是一种创建按钮的便捷方法(就像一个紧凑的alloc-init)。因此,它实际上“消除”了你过去的两行(你基本上创建了两次按钮)。您只能使用init或buttonWithType:作为相同的按钮,但不能同时使用两者。

UIButton *scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
scanQRCodeButton.frame = CGRectMake(0.0f, 5.0f, 320.0f, 44.0f);
scanQRCodeButton.backgroundColor = [UIColor redColor];
[scanQRCodeButton setTitle:@"Hello" forState:UIControlStateNormal];    
[cell addSubview:scanQRCodeButton];

这将有效(请注意,如果需要,可以使用cell.contentView)。如果您没有使用自动引用计数(ARC),我想提一下,您不必在内存管理方面做任何事情,因为buttonWithType:返回一个自动释放的按钮。

答案 1 :(得分:7)

    UIButton *deletebtn=[[UIButton alloc]init];
            deletebtn.frame=CGRectMake(50, 10, 20, 20);
            deletebtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            [deletebtn setImage:[UIImage imageNamed:@"log_delete_touch.png"] forState:UIControlStateNormal];
            [deletebtn addTarget:self action:@selector(DeleteRow:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:deletebtn];

//下载课程并导入项目UIButton+EventBlocks

UIButton *deletebtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[deletebtn setFrame:CGRectMake(170,5, 25, 25)];
deletebtn.tag=indexPath.row;
[deletebtn setImage:[UIImage imageNamed:@"log_delete_touch.png"] forState:UIControlStateNormal];
[deletebtn setOnTouchUpInside:^(id sender, UIEvent *event) {


  //Your action here
}];
[cell addSubview:deletebtn];

答案 2 :(得分:4)

您想要将任何自定义UI元素添加到单元格的contentView

所以,而不是[cell addSubview:scanQRCodeButton];[cell.contentView addSubview:scanQRCodeButton];

答案 3 :(得分:1)

尝试添加[cell.contentView addSubview:scanQRCodeButton];,或者如果您希望左侧的按钮在答案处查看my question,请将textLabel移到侧面。如果您希望按钮位于右侧,则只需将其设置为accesoryView,例如cell.accesoryView = scanQRCodeButton;

答案 4 :(得分:0)

方法setTitle在我的代码中不起作用,所以我使用

进行设置
[UIButton.titleLabel setText:@""]

而不是使用setTitle方法。

请使用以下代码重试:

[scanQRCodeButton.titleLabel setText:@"Hello"];

然后它会运作良好。

相关问题