在以往的列表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:
- #import <UIKit/UIKit.h>
- @interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
- @property (retain)NSArray *myList;
- @property (retain) IBOutlet UITableViewCell *myCell;
- @end
ViewController.m:
- #import "ViewController.h"
- @implementation ViewController
- @synthesize myList;
- @synthesize myCell;
- -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- {
- return [myList count];
- }
- -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString *tmpString=@"lll";
- UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:tmpString];
- if (cell==nil) {
- NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"xibView" owner:self options:nil];
- //这时myCell对象已经通过自定义xib文件生成了
- if ([nib count]>0) {
- cell = self.myCell;
- //加判断看是否成功实例化该cell,成功的话赋给cell用来返回。
- } else {
- NSLog(@"加载nib文件出错");
- }
- }
- NSInteger row=indexPath.row;
- UILabel *myLabel = (UILabel *)[cell viewWithTag:5 ];
- //这里的tag是在xib文件里面设的,用来找到我们设的label;
- myLabel.text=[myList objectAtIndex:row ];
- return cell;
- }
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- myList = [NSArray arrayWithObjects:@"不",@"图",@"不",@"挂", nil];
- }
- - (void)viewDidUnload
- {
- [super viewDidUnload];
- // Release any retained subviews of the main view.
- }
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
- {
- return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
- }
- @end
注意我们在自定义cell的xib时,可以手动拖拽设置每一行的高等,我们可以随便设,但是需要在ViewController.xib文件中将tableView的高也设为一样的,图中设的是107,修改相等;
xibView.xib:
viewController.xib
这样就可以实现自定义cell的效果了:
转自holydancer的优快云专栏,原文地址:http://blog.youkuaiyun.com/holydancer/article/details/7463682