iOS菜鸟学习——通过nib文件自定义Cell

首先,创建自定义cell的类,要继承于UITableViewCell。我们叫做CustomCell类。
   然后,创建新的view文件。我们叫这个文件为CustomCell.xib。然后打开CustomCell.xib,删除其中的view,添加一个UITableViewCell。点击cell,将cell的类由UITableViewCell改为CustomCell,将identifier改为CustomCell。这样,就可以自己定义控件,并在CustomCell中定义,并将他们连起来。然后,点击File's Owner文件,将Custom Class改为自己要用到这个cell 的UIViewController,我们叫它为ViewController。
   然后打开ViewController.h文件,创建两个属性变量 
[plain]
@property (strong, nonatomic) UINib *cellNib; 
@property (strong, nonatomic) IBOutlet CustomCell *customCell; 
     并且在ViewController.m文件中@synthesize,
[plain]
@synthesize customCell; 
@synthesize cellNib; 
   然后返回CustomCell.xib文件,右键点击File's Owner,将customCell与之前创建的cell连起来。
     最后,打开ViewController.m文件,在viewDidLoad方法中添加以下代码。
[plain]
self.cellNib = [UINib nibWithNibName:@"CustomCell" bundle:nil]; 
   在UITableView的tableView:cellForRowAtIndexPath中创建自己的cell,代码如下:
 
[plain]
static NSString *CellIdentifier = @"CustomCell"; 
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    [self.cellNib instantiateWithOwner:self options:nil]; 
    cell = customCell; 
    self.customCell = nil; 

   之后,就可以对自己在cell中添加的控件进行属性及内容的设置。
   这样,就实现了从nib文件来实现自定义cell。
   如有疏漏,请指出。

posted @ 2013-09-17 21:12  alincexiaohao  阅读(492)  评论(0编辑  收藏  举报