自定义UITableView(用控件)
快懒死了,赶紧到周末吧,赶紧发工资吧,赶紧过年吧......
饿死我了,穷死我了......
死之前发教程:
之前发过一篇完全自定义UITableView的教程,那篇用于每行不同的内容,但如果内容相同呢,就要用到表示图的重用性了。其实我鼓励大家完全用代码创建,这样便于维护和查错,但用IB可以缩短开发时间,鉴于本人非常懒,所以......
1.先创建一个继承于UITableViewCell的类MyCell
在MyCell.h文件中
#import <UIKit/UIKit.h> @interface MyCell : UITableViewCell { IBOutlet UIImageView *image; IBOutlet UILabel *label; } @property(retain,nonatomic)UIImageView *image; @property(retain,nonatomic)UILabel *label; @end
在MyCell.m文件中
#import "MyCell.h" @implementation MyCell @synthesize label,image; - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { // Initialization code } return self; } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; // Configure the view for the selected state } - (void)dealloc { [label release]; [image release]; [super dealloc]; } @end
代码搞定,再新创建一个空的xib文件,起名也为MyCell
在xib中添加一个控件Table View Cell
在如图添加其他控件吧
接下来连线,(注意:是myCell和文字和图片连接,不是file’s owner和文字和图片连接!)
连到这个地方.
然后改类的名字
再改重用的名字,要记住
类搞定了,再来看ViewController.h文件
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource> @end
Viewcntroller.m文件:
#import "ViewController.h" #import "MyCell.h" @implementation ViewController - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain]; tableView.delegate = self; tableView.dataSource = self; [self.view addSubview:tableView]; [tableView release]; } - (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"CellIdentifier";//这里的重用名一定要和控件定义的一样 MyCell *cell = (MyCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { NSArray *array = [[NSBundle mainBundle]loadNibNamed:@"MyCell" owner:self options:nil]; cell = [array objectAtIndex:0]; } [cell label].text = @"小白猪当家的玉照:"; [[cell label] sizeToFit]; [[cell image] setImage: [UIImage imageNamed:@"LittleWhitePig.png"]]; return cell; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 5; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 135; }
很简单吧,求关注,有问题留言哦