I need to create my own UITableViewCell using the xib file, to draw the graphic interface... what are the right steps to create my new class and to use into my UITableView?
thanks in advance
What are XIB files? From the point of view of the UI designer, XIB files contain the views or windows that you design in Interface Builder – the controls, their layout and properties, and their connections to your code. It is important to understand that on a technical level, XIB files are stored object graphs.
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.
In iOS5 you'll want to use the new:
registerNib:forCellReuseIdentifier
:
Which basically does the same thing...
Personally I think that both suggested tutorials have a big flaw when it comes to reuseIdentifier
. If you forget to assign it in interface builder or misspell it, you will load the nib each and every time cellForRowAtIndexPath
gets called.
Jeff LaMarche writes about this and how to fix it in this blog post. Apart from reuseIdentifier
he uses the same approach as in the apple documentation on Loading Custom Table-View Cells From Nib Files.
After having read all these articles I came up with following code:
Edit: If you are targeting iOS 5.0 and higher you'll want to stick with Duane Fields' answer
@interface CustomCellWithXib : UITableViewCell + (NSString *)reuseIdentifier; - (id)initWithOwner:(id)owner; @end @implementation CustomCellWithXib + (UINib*)nib { // singleton implementation to get a UINib object static dispatch_once_t pred = 0; __strong static UINib* _sharedNibObject = nil; dispatch_once(&pred, ^{ _sharedNibObject = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil]; }); return _sharedNibObject; } - (NSString *)reuseIdentifier { return [[self class] reuseIdentifier]; } + (NSString *)reuseIdentifier { // return any identifier you like, in this case the class name return NSStringFromClass([self class]); } - (id)initWithOwner:(id)owner { return [[[[self class] nib] instantiateWithOwner:owner options:nil] objectAtIndex:0]; } @end
UINib (available in iOS 4.0 and later) is used here as a singleton, because although the reuseIdentifier
is used, the cell still gets re-initialized about 10 times or so. Now cellForRowAtIndexPath
looks like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CustomCellWithXib *cell = [tableView dequeueReusableCellWithIdentifier:[CustomCellWithXib reuseIdentifier]]; if (cell == nil) { cell = [[CustomCellWithXib alloc] initWithOwner:self]; } // do additional cell configuration return cell; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With