Pavan
Pavan

Reputation: 18508

Correct way to setup a custom cell in the cellForRowAtIndexPath method?

Man, it's annoying how I have to keep referring back to my old xcode projects to find out how to setup a custom cell in my cellForRowAtIndexPath delegate method only because of the magnitude of methods I've seen.

What is the correct code for setting up a custom cell in the cellForRowAtIndexPath method without the use of storyboards?

I am currently doing something like this:

//This works for me btw
static NSString *simpleTableIdentifier = @"customcell";
CustomTableViewCell *customCell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (customCell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomTableViewCell" owner:self options:nil];
    customCell = [nib objectAtIndex:0];
}

Then I see other people using loadWithNibName and others that are registering their nibs in the viewDidLoad method using the registerWithNib method.

What in the world is the correct way to setup a custom cell in the delegate method?

I have also been told recently that I dont need to call the dequeueReusable.. method when I'm dealing with custom cells. Can someone please clarify the correct way to setup your cellForRowAtIndexPath delegate method once and for all for me. Without the use of story boards. I have correctly setup my custom cell view with its respective .m and .h files.

Upvotes: 0

Views: 223

Answers (1)

Prad
Prad

Reputation: 51

If it is CustomTableViewCell nib file exist in same UITableViewController nib your code will works fine. Otherwise you need to load nib file in cellForRowAtIndexPath:

if(cell==nil){
NSArray * nibContents = [[NSBundle mainBundle] loadNibNamed:"CustomTableViewCell" owner:self options:NULL];

NSEnumerator * nibEnumerator = [nibContents objectEnumerator];
NSObject * nibItem = nil;

while ((nibItem = [nibEnumerator nextObject]) != nil) {

    if ([nibItem isKindOfClass:[UITableViewCell class]]) {
        cell=(CustomTableViewCell*)nibItem;
    }

}

}

Upvotes: 1

Related Questions