Here is an example for creating custom .xib tableviewCell :-
Create a new file and when the window appears then first select USER INTERFACE from the menu appearing on left side and then select EMPTY file and create it. The .xib file will be created. Now drag a UITableViewCell and a UILabel into it. Create the outlet of the UILabel. After this create a new file which is subclass of UITableViewCell (here CustomCell) and assign this class to the CustomCell.xib file. Then in the attribute inspector give the Identifier of the cell (here customCell ).
In Main.Storyboard drag a UITableView and assign its datasource and delegate to the ViewController.
Now in the ViewController.m implement the following code :-
#import "ViewController.h"
#import "CustomCell.h"
@interface ViewController (){
NSArray *dataArray;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
dataArray = @[@Data , @to be , @"displayed"];
/* here we are registering nib file for cell */
[_tblView registerNib:[UINib nibWithNibName:@"MyCustomCell" bundle:nil] forCellReuseIdentifier:@"myCell"]; // _tblView is the outlet created on the UITableView
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)tableView :(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return dataArray.count; // returns the number of elements in the array
}
- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
cell.lblSecond.text = [items objectAtIndex:indexPath.row];
return cell;
}
@end
We can also add accessoryView to the UITableViewCell. If we want to display checkmark in first cell and details in all other cells then we can implement it as :-
- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
cell.lblSecond.text = [items objectAtIndex:indexPath.row];
NSLog(@"my first object == %@",[items objectAtIndex:indexPath.row]);
if (indexPath.row == 0) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryDetailButton;
}
return cell;
}
Modify the cellForRowAtIndexPath method as above. Build the program and see the results.
0 Comment(s)