UITableView的使用样例(简易向)

功能实现

  1. 构建一个UITableView,并使其默认显示a,b,c……..
  2. 构建一个按钮,点击后列表变为英文字母
  3. 构建一个按钮,点击后列表变为数字

基本概念

  1. 实现前头文件需要签订协议(如何签订向后看)UITableViewDateSource,UITableViewDelegate
  2. 实现UITableView必须实现的两个方法

返回:

 UITableView中的section总行数

参数:
section:表示section下标

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

返回:
UITableView所有单元格(虽然在方法中是返回其中之一个单元格,但程序中它可以通过indexPath参数从0到最后循环运行下去)
参数:
indexPath:表示行的下标,可利用来读取数组的制定数据

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

实现过程

1.在storyboard拖拽一个UITableView,两个UIButton,然后做好相关的参数设置(签订协议不要忘了)。

实现:签订协议

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
@end

实现:定义变量

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tvTable;
@property (strong, nonatomic) NSMutableString * string;
@end

2.viewDidLoad方法的实现
实现:string的先初始化为英文字母的字符串

-(void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.string = [[NSMutableString alloc]init];
    for (int i = 0; i < 26; i ++) {
        [self.string appendFormat:@"%c",'a'+i ];//字符串末尾加上一个字符
    }
    [self.tvTable setDataSource:self];
    [self.tvTable setDelegate:self];
}

3.实现两个必须实现的方法
实现:

  1. UITableView设定单元格个数为20个

  2. 将string字符串中的数据输入单元格

//返回单元格的数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  20;
}

//创建单元格
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    static NSString *identifier = @"myCell";

    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];

    cell.textLabel.text = [NSString stringWithFormat:@"%c",[self.string characterAtIndex:indexPath.row]];

    return cell;
}

4.实现两个按键的action

- (IBAction)eventChange2Words:(UIButton *)sender {
    self.string = [NSMutableString stringWithFormat:@""];
    for (int i = 0; i < 26; i ++) {
        [self.string appendFormat:@"%c",'a'+i ];
    }
    [self.tvTable reloadData];
}
- (IBAction)eventChange2Nums:(UIButton *)sender {
    self.string = [NSMutableString stringWithFormat:@""];
    for (int i = 0; i < 26; i ++) {
        [self.string appendFormat:@"%c",'0'+(i%10) ];
    }
    [self.tvTable reloadData];
}

样例结果

图中显示的是显示字母的功能,显示数字的功能其实大同小异,请自行脑补
这里写图片描述

已知缺陷

  1. 如果string长度小于20时程序会崩溃,因为在 - (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath中访问时访问string字符串的下标从0到19
  2. 你们不觉得这好丑么。。。。。

推荐阅读

OS开发系列–UITableView全面解析
http://www.cnblogs.com/kenshincui/p/3931948.html#uiTableViewCell

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值