iOS開發-UITableView自定義Cell

UITableView在iOS中開發的重要地位是毋庸置疑的,基本上應用中用到的比例是一半左右,並且大部分狀況都是須要自定義單元格的,這樣用戶看到的App才能更有美感。以前寫過UITableView的基本用法,若是對UITableView不是很熟悉能夠參考本人以前的博客,所以不少UITableView的知識點就默認你已經熟悉了,先看下自定義實現的效果,這是自定義的Cell最後展示的效果:數組

 

自定義Cell

1.首先新建一個CustomCell.xib文件,方式以下:ide

 

2.新建一個繼承自UITableViewCell的CustomTableViewCell類,須要重寫initWithStyle方法:atom

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil];
    self=[views firstObject];
    }
    return self;
}

3.CustomCell.xib中拖入一個UITableViewCell,而後和CustomTableViewCell關聯:spa

關聯以後CustomTableViewCell多了一個屬性:blog

@property (weak, nonatomic) IBOutlet UILabel *title;

UITableView加載Cell

1.viewDidLoad初始化UITableView:繼承

    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(10, 10,CGRectGetWidth(self.view.bounds)-20, CGRectGetHeight(self.view.bounds)-10)];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.view addSubview:self.tableView];

2.初始化標題數組travelArr開發

-(NSArray *)travelArr{
    _travelArr=@[@"北京-清邁",@"北京-香港",@"北京-東京",@"北京-大阪",@"北京-新加坡",@"北京-維多利亞",@"北京-紐約",@"北京-夏威夷",@"北京-維多利亞",@"北京-柬埔寨"];
    return _travelArr;
}

3.實現UITableViewDataSource中的方法: 博客

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.travelArr count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static  NSString  *identifier=@"CustomCell";
    CustomTableViewCell  *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell=[[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.title.text=[self.travelArr objectAtIndex:indexPath.row];
    return cell;
}

4.實現UITableViewDelegate中的方法:it

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

簡單的自定義大概就是如此了,若是有所收穫,幫忙推薦下~io

相關文章
相關標籤/搜索