holydancer原创

 

在以往的列表tableView中,我们习惯都是使用代码生成一个cell来显示每一行,其实我们也可以用xib构造出一个,然后使用该自定义的cell来作为每一行的样式;

首先按传统的方法在viewController的xib文件中拉上去一个tableView,然后将该tableView的数据源和委托都拖到viewController上。然后在viewController.h中声明两个协议,然后在viewController.m中实现两个方法(我们不响应点击行的事件了),这样就可以简单达到显示列表的目的。这都和传统的一样,这时我们需要在viewController.h中声明一个输出口,类型为UITableViewCell类型作为我们自定义的cell,再new一个xib文件出来,里面拖上一个UITableViewCell控件,将该xib文件的所有者也设为viewController.m,注意这时viewController.m是两个xib文件的委托。将该UITableViewCell与输出口对接,这样如果我们实例化该xib文件的话,我们的输出口对象就会生成,将其作为cell即可。

ViewController.h:

 


1. #import <UIKit/UIKit.h>  
2.   
3. @interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>  
4. @property (retain)NSArray *myList;  
5. @property (retain) IBOutlet UITableViewCell *myCell;  
6. @end



ViewController.m:

 

 

1. #import "ViewController.h"  
2.   
3.   
4. @implementation ViewController  
5. @synthesize myList;  
6. @synthesize myCell;  
7.   
8.   
9. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
10. {  
11.     return [myList count];  
12. }  
13.   
14. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
15. {  
16.     static NSString *tmpString=@"lll";  
17.     UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:tmpString];  
18.     if (cell==nil) {  
19.        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"xibView" owner:self options:nil];  
20.         //这时myCell对象已经通过自定义xib文件生成了  
21.         if ([nib count]>0) {  
22.             cell = self.myCell;  
23.             //加判断看是否成功实例化该cell,成功的话赋给cell用来返回。  
24.         } else {  
25.             NSLog(@"加载nib文件出错");  
26.         }  
27.     }  
28.     NSInteger row=indexPath.row;  
29.     UILabel *myLabel = (UILabel *)[cell viewWithTag:5 ];  
30.     //这里的tag是在xib文件里面设的,用来找到我们设的label;  
31.     myLabel.text=[myList objectAtIndex:row ];  
32.     return cell;  
33.       
34. }  
35.   
36. - (void)viewDidLoad  
37. {  
38.     [super viewDidLoad];  
39.     myList = [NSArray arrayWithObjects:@"不",@"图",@"不",@"挂", nil];  
40. }  
41.   
42. - (void)viewDidUnload  
43. {  
44.     [super viewDidUnload];  
45.     // Release any retained subviews of the main view.  
46. }  
47.   
48. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
49. {  
50.     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);  
51. }  
52.   
53. @end



注意我们在自定义cell的xib时,可以手动拖拽设置每一行的高等,我们可以随便设,但是需要在ViewController.xib文件中将tableView的高也设为一样的,图中设的是107,修改相等;

 

xibView.xib:

Iphone开发(十二)通过xib文件自定义列表中的行_移动开发

viewController.xib

Iphone开发(十二)通过xib文件自定义列表中的行_移动开发_02

这样就可以实现自定义cell的效果了:

Iphone开发(十二)通过xib文件自定义列表中的行_移动开发_03

 

关键字:IOS ,Iphone 开发 ,Iphone SDK ,自定义列表 ,UITableViewCell ,holydancer