Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create custom tableViewCell from xib

I want to create a custom TableViewCell on which I want to have UITextField with editing possibility. So I created new class with xib. Add TableViewCell element. Drag on it UITextField. Added outlets in my class and connect them all together. In my TableView method cellForRowAtIndexPath I create my custom cells, BUT they are not my custom cells - they are just usual cells. How can I fix this problem, and why it is? thanx!

//EditCell. h

#import <UIKit/UIKit.h>


@interface EditCell : UITableViewCell
{
    IBOutlet UITextField *editRow;
}
@property (nonatomic, retain) IBOutlet UITextField *editRow;
@end

//EditCell.m

#import "EditCell.h"


@implementation EditCell
@synthesize editRow;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidUnload 
{
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
    self.editRow = nil; 
}
@end

//in my code

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"EditCell";

    EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[EditCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                reuseIdentifier:CellIdentifier] autorelease];
    }
cell.editRow.text = @"some text to test";
return cell;
}
like image 797
yozhik Avatar asked Nov 16 '10 15:11

yozhik


People also ask

How do I register a nib file in Swift?

viewDidLoad() let nib = UINib(nibName: "MyCustomCell", bundle: nil) myTable. register(nib, forCellReuseIdentifier: "MyCustomCell") myTable. dataSource = self } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.

How do you make a table view with multiple cell types?

storyboard and drag and drop a TableView inside your View Controller. Now, select the table view and go to the identity inspector. Set the "Prototype Cells" to 3. Here, you just told your TableView that you may have 3 different kinds of cells.


1 Answers

Do not use UITableViewCell's initializer, but make the cell load from your nib:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"EditCell";

    EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"YourNibNameHere" owner:self options:nil];
        cell = (EditCell *)[nib objectAtIndex:0];
    }
    cell.editRow.text = @"some text to test";
    return cell;
}

Of course, you need to specify the correct nib name.

like image 188
Björn Marschollek Avatar answered Sep 21 '22 03:09

Björn Marschollek