我想在 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];
}`
现在,当我运行该应用程序时,我只看到一个空白行!有什么想法吗?
最佳答案
虽然将它放在单元格的 contentView 中很自然,但我相当确定这不是问题(实际上,在过去,我从未在 contentView 中正确显示 subview ,所以我总是使用了电池)。
无论如何,问题涉及开始创建按钮时的前三行。前两行没问题,但代码停止工作:
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: 返回一个自动释放的按钮。
关于iphone - 将按钮添加到 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8836563/