现在我处于学习阶段,写这些笔记既是为了自己,也希望帮助正在学习的你。但是,亲们,我发现写文章太浪费时间了,以后直接用代码吧。不明白的可以留言。
项目的目录如下图:
步骤:
1、新建一个“Single View Application”的项目,命名XibDemoUITableView
2、WJTableViewCell 这个类 继承自 UITableViewCell,当WJTableViewCell里面的成员变量要在其他类中被访问时,需要设置为该类的属性 (即:在.h文件中@property.... , 在.m文件中 @synthesize....)
WJTableViewCell.h文件代码
#import <UIKit/UIKit.h>
@interface WJTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *mylabel;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@end
WJTableViewCell.m文件代码
@synthesize mylabel;
@synthesize label2;
3、在 ViewController.xib中拖入 一个 UITableView,并且要设置代理
选中“File's Owner”---------> 选中右边最上面第六个箭头图标 -----------> 将“Referencing Outlets”下的两个代理连接到 “File's Owner”(点中空心圆圈,将箭头指向“File's Owner”即可)
4、在ViewController.h 中遵循UITableView的两个代理
@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
5、在ViewController.m 中 由于比较重要,将源代码贴出来。
#import "ViewController.h"
#import "WJTableViewCell.h"
@interface ViewController ()
@end
@implementation ViewController{
NSArray * myData;
//自定义数组,用于存放UITableViewCell中要显示的数据
}
static NSString * cellId = @"identifier";
- (void)viewDidLoad
{
[super viewDidLoad];
myData = @[@"111111",@"222222",@"333333"];
//给tableView注册一个xib当cell
[_myTableView registerNib:[UINib nibWithNibName:@"WJTableViewCell" bundle:nil] forCellReuseIdentifier:cellId];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark -
#pragma mark - UITableViewDataSource/UITableViewDelegate
//返回几行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return myData.count;
}
//返回tableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//dequeueReusableCellWithIdentifier 这个方法不能想当然,很容易写错
WJTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
// if (nil == cell) {
// cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
// }
// cell.textLabel.text = myData[indexPath.row];
cell.mylabel.text = myData[indexPath.row];
cell.label2.text = @"shijdksd";
return cell;
}
@end