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

查看:19
本文介绍了将按钮添加到 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天全站免登陆