Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using my own Cell object in XCODE

I have successfully created my on "cell" object (based on UITableViewCell) and have successfully used it while building a table via cellForRowAtIndexPath.

However, how do I deconstruct what I have done within didSelectRowAtIndexPath?

I currently receive the error "Incompatible pointer types initializing 'MyCell *__strong' with an expression of type 'UITableViewCell'"

Given my object (MyCell) is based on UITableViewCell I don't understand why I am getting this error.

Can you please help me understand what I am doing wrong.

My alternative is to use a "TAG" for each of the two labels in the cell and get them that way, but I am just experimenting here trying to learn more about how this all works.

Any help would be greatly appreciated.

- (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;
}

Here is the other method. I get the error on 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];

}

And here is MyCell

#import <UIKit/UIKit.h>

@interface MyCell : UITableViewCell

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

@end

Any help would be appreciated.

like image 919
David Avatar asked Jan 15 '23 05:01

David


2 Answers

Change this:

MyCell *cell = [tableView cellForRowAtIndexPath:indexPath];

to the following:

MyCell *cell = (MyCell *) [tableView cellForRowAtIndexPath:indexPath];
like image 164
user427969 Avatar answered Jan 29 '23 12:01

user427969


I think you just need to cast the UITableViewCell* to MyCell*

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

Everything else looks ok to me.

Typically I wouldn't get the cell information by calling cellForRowAtIndexPath, I would instead get it from the underlying data model.

like image 36
EarlyRiser Avatar answered Jan 29 '23 14:01

EarlyRiser