Add button to UITableViewCell(将按钮添加到 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将按钮添加到 UITableViewCell
基础教程推荐
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01