添加按钮到UITableViewCell [英] Add button to UITableViewCell

查看:89
本文介绍了添加按钮到UITableViewCell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add a button in a UITableViewCell. This is my code: `

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];
}`

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

Now, when I run the app, I see only a blank row ! Any ideas ?

推荐答案

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

While it's natural to put it in the contentView of the cell, I'm fairly certain that is not the problem (actually, in the past, I've never had subviews displayed correctly in the contentView, so I've always used the cell).

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

Anyway, the problem involves the first three lines of when you start creating your button. The first two lines are fine, but the code stops working with:

scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

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

buttonWithType: is actually a convenience method to create a button (it's like a compact alloc-init). Therefore, it actually "nullifies" your past two lines (you basically created the button twice). You can only use either init or buttonWithType: for the same button, but not both.

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:返回一个自动释放的按钮。

This will work (note that you can use cell.contentView if you wanted). In case you're not using Automatic Reference Counting (ARC), I would like to mention that you don't have to do anything in term of memory management, because buttonWithType: returns an autoreleased button.

这篇关于添加按钮到UITableViewCell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆