【问题标题】:Using my own Cell object in XCODE在 XCODE 中使用我自己的 Cell 对象
【发布时间】:2012-10-14 03:11:09
【问题描述】:

我已经成功创建了我的“单元格”对象(基于 UITableViewCell)并在通过 cellForRowAtIndexPath 构建表格时成功使用了它。

但是,我如何解构我在 didSelectRowAtIndexPath 中所做的事情?

我目前收到错误“使用 'UITableViewCell' 类型的表达式初始化 'MyCell *__strong' 的指针类型不兼容”

鉴于我的对象 (MyCell) 基于 UITableViewCell,我不明白为什么会出现此错误。

你能帮我理解我做错了什么吗?

我的替代方法是为单元格中的两个标签中的每一个都使用一个“TAG”并以这种方式获取它们,但我只是在这里进行试验,试图了解更多关于这一切是如何工作的。

任何帮助将不胜感激。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"myCellID";
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[MyCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:CellIdentifier];
    }

cell.accountCode.text = @"0009810";
cell.accountName.text = @"Agent Name";

return cell;
}

这是另一种方法。我在 MyCell *cell = [tableView cellForRowAtIndexPath:indexPath];

上收到错误
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

// Get the cell that was selected
MyCell *cell = [tableView cellForRowAtIndexPath:indexPath];

AccountRecord *accountRecord = [[AccountRecord alloc] init];
accountRecord.accountCode = cell.accountCode.text;
accountRecord.accountName = cell.accountName.text;

[self performSegueWithIdentifier:@"AccountDetail" sender:accountRecord];

}

这是我的细胞

#import <UIKit/UIKit.h>

@interface MyCell : UITableViewCell

@property (nonatomic,strong) IBOutlet UILabel *accountCode;
@property (nonatomic,strong) IBOutlet UILabel *accountName;

@end

任何帮助将不胜感激。

【问题讨论】:

    标签: ios xcode uitableview cell


    【解决方案1】:

    改变这个:

    MyCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    

    到以下:

    MyCell *cell = (MyCell *) [tableView cellForRowAtIndexPath:indexPath];
    

    【讨论】:

    • 哇哦。这么容易?所以我想这基本上是将结果“投射”到我的对象上?
    • 是的,您需要投射它,因为您使用的是自定义单元格。
    • 优秀。那成功了。非常感谢您几乎立即回复我的帖子。 :-)
    【解决方案2】:

    我认为你只需要将 UITableViewCell* 转换为 MyCell*

    MyCell *cell = (MyCell*)[tableView cellForRowAtIndexPath:indexPath];
    

    在我看来其他一切都很好。

    通常我不会通过调用 cellForRowAtIndexPath 来获取单元格信息,而是从底层数据模型中获取它。

    【讨论】:

    • 感谢您的回复。关于您使用底层数据模型的建议,我似乎有很多使用数组来保存所有表数据的例子。我有多达几千行(通过简单的搜索功能帮助用户找到它们)。我在想构建一个包含所有信息的数组以及它在表中的内存真的加倍。因此,我正在考虑从表格中获取信息以转到下一个 VC,而不是查看数据模型。我是不是应该不用担心内存并使用数组方法?
    • 无论如何,屏幕上的单元格数量都与屏幕大小一样多。它们在离开屏幕时被回收并用于显示下一个出现在屏幕上的元素。首先,您总是需要某种方法将数据填充到单元格中,因此您应该能够在 didSelectRowAtIndexPath 中使用该机制,而不是获取单元格。
    猜你喜欢
    • 2012-01-03
    • 1970-01-01
    • 2017-04-22
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    相关资源
    最近更新 更多