zoukankan      html  css  js  c++  java
  • iOS开发-UITableView自定义Cell

    UITableView在iOS中开发的重要地位是毋庸置疑的,基本上应用中用到的比例是一半左右,而且大部分情况都是需要自定义单元格的,这样用户看到的App才能更有美感。之前写过UITableView的基本用法,如果对UITableView不是很熟悉可以参考本人之前的博客,因此很多UITableView的知识点就默认你已经熟悉了,先看下自定义实现的效果,这是自定义的Cell最后展现的效果:

    自定义Cell

    1.首先新建一个CustomCell.xib文件,方式如下:

    2.新建一个继承自UITableViewCell的CustomTableViewCell类,需要重写initWithStyle方法:

    -(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关联:

    关联之后CustomTableViewCell多了一个属性:

    @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中的方法:

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

    简单的自定义大概就是如此了,如果有所收获,帮忙推荐下~

  • 相关阅读:
    关于lockkeyword
    关于多层for循环迭代的效率优化问题
    Android 面试精华题目总结
    Linux基础回想(1)——Linux系统概述
    linux源代码编译安装OpenCV
    校赛热身 Problem C. Sometimes Naive (状压dp)
    校赛热身 Problem C. Sometimes Naive (状压dp)
    校赛热身 Problem B. Matrix Fast Power
    校赛热身 Problem B. Matrix Fast Power
    集合的划分(递推)
  • 原文地址:https://www.cnblogs.com/xiaofeixiang/p/4457350.html
Copyright © 2011-2022 走看看