[iOS开发必备技巧之]使用IB定制UITableViewCell

来源:互联网 发布:表格相同数据合并 编辑:程序博客网 时间:2024/05/29 19:38


 [iOS开发必备技巧之]使用IB定制UITableViewCell


     我们在做ios开发的时候 ,随时都会使用到uitableview,这时定制每个CELL就变成 了一项很头痛的差事,因为如果每个CELL都要去计算,不断的调度frame的话,这将会花费很多时间,而且效果也不一定很好,所以使用IB来定制UITableViewCell就成了我们日常开发中必备的技巧之一,下面我们就一起来看一下如何完美的实现使用IB来定制UITableViewCell。
1.在IB中构建Cell的SubView
如下图示:




这里有几点需要注意:
A.这个xib的长宽需要与UITableView 的行高匹配,不得高于了每行的高度,当然宽度也一样不能超过UITableView的宽度.
B.这里一定要指明Identifier,否则,UITableViewCell将不会重用,每加载一行都会全新的加载,浪费系统资源。
C.如果重写一个Custom UITableViewCell如下:

@interface LoginInputCell : UITableViewCell {IBOutlet UILabel *iLabel;IBOutlet UITextField *iTextField;}@property (nonatomic, retain) IBOutlet UILabel *iLabel;@property (nonatomic, retain) IBOutlet UITextField *iTextField;

2.在代码中需要导入xib,然后对其再做相应的定制操作。

- (UITableViewCell *)tableView:(UITableView *)tableView          cellForRowAtIndexPath:(NSIndexPath *)indexPath {    static NSString *CellIdentifier = @"CustomTableCell";    static NSString *CellNib = @"CustomTableCellView";    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];    if (cell == nil) {        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil];        cell = (UITableViewCell *)[nib objectAtIndex:0];    }    // perform additional custom work...    return cell;}
这需要注意的几点:

1.要使用Cell能够重用,需要指定IB中那个identifier,如上代码所示。

2.如果你重写UITableViewCell,则这里就可以直接操作了。如:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {static NSString *CellIdentifier = @"CustomCell";static NSString *CellNib = @"LoginInputCell";int section = [indexPath section];int row = [indexPath row];LoginInputCell *cell = (LoginInputCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];if (cell == nil){NSArray* array = [[NSBundle mainBundle] loadNibNamed:CellNib   owner:self  options:nil];cell = (LoginInputCell *)[array objectAtIndex:0];}//u can do this cell.iLabel.text = @"xxxx";cell.iTextField.tag = 101;cell.iTextField.delegate = self;[cell.iTextField setReturnKeyType:UIReturnKeyNext];}

3.如果你没有重写UITableViewCell,那你如何定制每一行的Cell呢,使用如下方法:

#define TEXTLABEL((UILabel *)[cell viewWithTag:101])- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath{UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:@"BaseCell"];if (!cell) cell = [[[NSBundle mainBundle] loadNibNamed:@"BaseCell" owner:self options:nil] lastObject];[TEXTLABEL setText:[[UIFont familyNames] objectAtIndex:indexPath.row]];return cell;}

这里虽然使用的UILabel,其它控件的使用方法同样如此哈。

以上两种获取Cell中控件的方法都是可以的,可能第二种更加简单。



原创粉丝点击