iphone - 将按钮添加到 UITableViewCell

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

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

最佳答案

虽然将它放在单元格的 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/

相关文章:

ios - Xcode 8 约束

iphone - UITableView 自定义部分标题显示在单元格下方

ios - 其中一些带有 UIImageView 的 UITableViewCell

uitableview - 有没有办法改变 UICollectionViews 的动画速度?

iphone - 有没有办法使用 CFStreamCreatePairWithSocketToHost() 获取套接字引用?

iphone - 从 NSMutableArray 获取记录时 Indexpath.row 不工作

php - 带有特殊字符的 NSURL (åäö)

ios - MetricKit MXCallStackTree 符号

iphone - 我如何在我的 iphone 应用程序中验证 obj c 中的这个简单条件

iphone - 阻止 iCloud 同步数据(使用 .nosync?)