TableView Summary

本文详细介绍了如何在iOS开发中使用TableView,并提供了创建自定义单元格的方法,包括基本列表的实现、分区列表的概念、创建自定义单元格的步骤以及使用xib文件自定义单元格的技巧。


Tableview 在ISO中的使用很频繁,我也是刚刚学习ISO开发,就些想就TableView总结一下。有什么错误或补充请大家提出来,Welcome your valuable comments.;)


一、简单的列表。

在开发之前我想大家应该知道TableView有两个重要的委托:UITableViewDataSources, UITableViewDelegate.

这两个一个是提供表的数据模型的,一个是实现选择区域,配置分区头和尾,帮助删除和记录单元格并且执行其它动作(翻译而来)。

UITableViewDataSources 中有两个必须提供的两个方法:

- (NSInteger) tabelView:(UITableView *)tableView numberOfRowInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath;

其中也有许多可选的实现方法:设置行的高度或者显示的缩进,分区,可编辑,可移动等等,这些根据实际的要求自己重写这方法。

这里的分区的意思我简单说下。有三种简单列表 一个是无分区的列表,一个是有分区的列表(例:联系人-根据A-Z分组),还有是一个有分区带索引的列表(例:联系人-根据字母分组且右边列出了一列很小的26个字母)。

这里我只实现一个没有分区的简单列表。

TableView 必须要嵌套在TableViewController里,否则会提示出错,或者不能显示单元格。

创建一个single-view 的applicaton然后有个ViewController它是UIViewController的子类,我们修改在为UITableViewController<UITableViewDataSources,UITableViewDelegate>

然后在object library中选择TableView拖放到ViewController中。

<img src="https://img-blog.csdn.net/20150713105211720?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
这里最重要的是tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath;

代码中创建单元格(Default)并且设置一个图片。


二、创建一个自定义的表格

系统有提供三个类型的单元格,但有时候我们这三种类型的单元格不能满足我们的要求,需要我们自己创建自己想要的单元格。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if(cell==nil)
    {
        CGRect cellframe=CGRectMake(0, 0, 300, 65);
        cell=[[UITableViewCell alloc] initWithFrame:cellframe];
        //add Name label
        CGRect nameLabelRect=CGRectMake(0, 5, 70, 15);
        UILabel *nameLabel=[[UILabel alloc]initWithFrame:nameLabelRect];
        nameLabel.textAlignment=NSTextAlignmentCenter;
        nameLabel.text=@"Name";
        nameLabel.font=[UIFont boldSystemFontOfSize:12];
        [cell.contentView addSubview:nameLabel];
        
        //add Color Label
        CGRect colorLabelRect=CGRectMake(0, 26, 70, 15);
        UILabel *colorLabel=[[UILabel alloc]initWithFrame:colorLabelRect];
        colorLabel.textAlignment=NSTextAlignmentCenter;
        colorLabel.text=@"Color";
        colorLabel.font=[UIFont boldSystemFontOfSize:12];
        [cell.contentView addSubview:colorLabel];
        
        CGRect nameValueRect=CGRectMake(80, 5, 200, 15);
        UILabel *nameValue=[[UILabel alloc] initWithFrame:nameValueRect];
        nameValue.textAlignment=NSTextAlignmentCenter;
        nameValue.tag=kNameValueTag;
        nameValue.text=[[self.computers objectAtIndex:indexPath.row] objectForKey:@"Name"];
        nameValue.font=[UIFont boldSystemFontOfSize:12];
        [cell.contentView addSubview:nameValue];<pre name="code" class="objc">
CGRect colorValueRect=CGRectMake(80, 25, 200, 15); UILabel *colorValue=[[UILabel alloc] initWithFrame:colorValueRect]; colorValue.textAlignment=NSTextAlignmentCenter; colorValue.tag=kNameValueTag; colorValue.text=[[self.computers objectAtIndex:indexPath.row] objectForKey:@"Color"]; colorValue.font=[UIFont boldSystemFontOfSize:12]; [cell.contentView addSubview:colorValue]; }


其它与简单列表设置一样,这里的实现方法有点不同,代码直接创建UI对象然后通过方法cell.contentView addSubView将对象添加到视图中。

这个方法比较繁琐还需要计算对象在视图中的位置。

下面介绍另一种方法通过创建一个xib视图文件来自定义自己的单元格。

首先我们创建xib文件,然后拖放一个TableView Cell对象,然后添加相应的控件到TableViewCell中,这里我只绑定两个标签。

然后我们要创建自己的单元格的数据模型。这个我们需要继承UITableViewCell

@interface CustomCell : UITableViewCell
{
    IBOutlet UILabel *_nameLabel;
    IBOutlet UILabel *_colorLabel;
}

@property (nonatomic,retain)UILabel *nameLabel;
@property (nonatomic,retain)UILabel *colorLabel;
@end

下面就是主表中实现代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    NSDictionary *dicRow1=[[NSDictionary alloc] initWithObjectsAndKeys:@"MacBook",@"Name",@"White",@"Color", nil];
    NSDictionary *dictRow2=[[NSDictionary alloc] initWithObjectsAndKeys:@"MacBook Pro",@"Name",@"Silver",@"Color",nil];
     NSDictionary *dictRow3=[[NSDictionary alloc] initWithObjectsAndKeys:@"MacBook Air",@"Name",@"White",@"Color",nil];
    NSArray *array=[[NSArray alloc] initWithObjects:dicRow1,dictRow2,dictRow3, nil];
    self.computers=array;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


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


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 static NSString * identifier=@"CustomCellIdentifier";
    CustomCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if(cell==nil)
    {
        //Nib file
        NSArray *nib=[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        cell=[nib objectAtIndex:0];
    }
    NSUInteger row=[indexPath row];
    NSDictionary *rowData=[self.computers objectAtIndex:row];
    cell.nameLabel.text=[rowData objectForKey:@"Name"];
    cell.colorLabel.text=[rowData objectForKey:@"Color"];
    return cell;
}





分析下面代码的逻辑,但这个页面完成最后设置时,需要解决下面的bug bug信息: Bug 1174015 - 【quick setup】iOS standalone添加ap,quick setup最后一步summary页控件依然显示为Next,安卓为“Confirm”引导更合理 (edit) 基本信息 ► 审核区域▼ Status: ASSIGNED (edit) Importance: major (edit) Bug的类别: UI (edit) 出现频率: 必然 (edit) 能否恢复: --- (edit) 测试拓扑: (edit) 陪测设备: (edit) 重现步骤: iOS standalone添加ap,quick setup到最后一步summary页,观察 (edit) 测试结果: 控件依然显示为Next (edit) 期望结果: 显示为confirm (edit) 问题产品: (edit) 对比测试: Android显示为confirm (edit) 问题分析: 请分析 (edit) 影响评估: 双端不一致 (edit) 代码: // // StandaloneQuickSetupSummaryViewController.m // Omada // // Created by zhuangqiuxiong on 2018/1/8. // Copyright © 2018年 TP-Link. All rights reserved. // #import "StandaloneQuickSetupSummaryViewController.h" #import "VMSLQuickSetupSummary.h" #import "StandaloneQuickSetupApplySettingsViewController.h" #import "TPSLQuickSetupUserAbstractLayer.h" #import "standaloneQuickSetupFlexibleBar.h" @interface StandaloneQuickSetupSummaryViewController ()<UITableViewDelegate> @property (nonatomic, strong) UITableView *tableView; @property (nonatomic, strong) VMSLQuickSetupSummary *vmTableViewDataSource; @property (nonatomic, strong) StandaloneQuickSetupFlexibleBar *flexibleBar; @property (nonatomic, strong) UIButton *nextButton; @property (nonatomic, assign) BOOL isForGateway; @end @implementation StandaloneQuickSetupSummaryViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self setupNavigationItem]; [self buildTableView]; [self buildFlexibleBar]; } - (void)buildTableView { self.tableView = [TPBCommonTableHelper createKeyboardAvoidingTableViewWithDelegate:self andDataSource:nil]; // self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped]; [self.view addSubview:self.tableView]; // self.tableView.delegate = self; // self.tableView.estimatedRowHeight = 72; // self.tableView.estimatedSectionHeaderHeight = 0; // self.tableView.estimatedSectionFooterHeight = 0; // self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; // self.tableView.separatorInfo.separatorStyle = TPTableViewSeparatorDetailStyle; // self.tableView.tableFooterView = [[UIView alloc] init]; // self.tableView.backgroundColor = [UIColor tpbBackground]; self.vmTableViewDataSource = [[VMSLQuickSetupSummary alloc] init]; self.tableView.dataSource = self.vmTableViewDataSource; [self.vmTableViewDataSource registerClassInTableView:self.tableView]; UIButton *nextButton = [[UIButton alloc] init]; if (nextButton) { [self.view addSubview:nextButton]; [nextButton setBackgroundColor:[UIColor tpbPrimary]]; nextButton.layer.cornerRadius = 22; [nextButton setTitle:gStandaloneQuickSetup.standaloneQuickSetupSetAccountNavRightButton forState:UIControlStateNormal]; nextButton.titleLabel.font = [UIFont tpr20Regular]; nextButton.titleLabel.textColor = [UIColor tpbTextWhite]; [nextButton addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside]; TPWeakSelf; [nextButton mas_makeConstraints:^(MASConstraintMaker *make) { TPStrongSelf; make.leading.mas_equalTo(_self.view).offset(20); make.trailing.mas_equalTo(_self.view).offset(-20); make.height.equalTo(@(44)); make.bottom.equalTo(self.mas_tpSafeAreaLayoutGuide).offset(-8); }]; self.nextButton = nextButton; } TPWeakSelf; [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) { TPStrongSelf; make.top.leading.trailing.equalTo(self.mas_tpSafeAreaLayoutGuide); make.bottom.equalTo(self.nextButton.mas_top).offset(-2); }]; } - (void)buildFlexibleBar { CGFloat maxBarHeight = kFlexibleBar_MinHeight + 50.0f; CGFloat minBarHeight = kFlexibleBar_MinHeight; self.flexibleBar = [[StandaloneQuickSetupFlexibleBar alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, maxBarHeight) andMaximumBarHeight:maxBarHeight andMinimumBarHeight:minBarHeight andElasticMaximumHeightAtTop:NO andViewController:self andScrollView:self.tableView]; if ( self.flexibleBar ) { [self.view addSubview:self.flexibleBar]; self.flexibleBar.titleString = gStandaloneQuickSetup.standaloneQuickSetupSummaryNavTitle; [self.flexibleBar setupSubViewsAndLayoutAttributes]; // self.flexibleBar.backgroundColor = [UIColor tpbBackground]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.tpbPrivacyProtectionEnabled = YES; [self.vmTableViewDataSource reloadData]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } #pragma mark - TableView Delegate - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { // return 40; return UITableViewAutomaticDimension; } - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { return [self.vmTableViewDataSource viewForSectionHeaderInSection:section]; } - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { // return 0.01; return TPBDesign.list.sectionFooterHeight; } - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section { return [UIView new]; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; } #pragma mark - 导航栏相关 - (void)setupNavigationItem { // [self setNavigationBarTitle:gStandaloneQuickSetup.standaloneQuickSetupSummaryNavTitle]; // [self.tpNavigationController setNavigationBarTitleFont:[UIFont tpr20Regular] andColor:[UIColor tpbTextPrimary]]; self.isNavigationBarTransparent = YES; UIBarButtonItem *leftBarButtonItem = [self createBarButtonItemItemWithStyle:TPViewControllerBarButtonItemStyleBackInBlue andTarget:self andAction:@selector(back)]; self.navigationItem.leftBarButtonItem = leftBarButtonItem; } - (void)back { [self.tpNavigationController popViewControllerAnimated:YES]; } - (void)next { TPWeakSelf; [self showWaitingToastView]; [[[ALStandaloneDeviceContext currentInstance] checkLoginStatus] addCompletionOnMainThread:^(TPHandleResult *result) { TPStrongSelf; [_self dismissToastViewWithCompleteBlock:^{ if (result.success) { if (self.isForGateway) { // 跳转到Gateway页面 [_self.tpNavigationController pushViewControllerWithCustomAnimation:[[StandaloneQuickSetupApplySettingsViewController alloc] initForGateway:self.isForGateway] animated:YES]; } else { // 跳转到EAP页面 [_self.tpNavigationController pushViewControllerWithCustomAnimation:[[StandaloneQuickSetupApplySettingsViewController alloc] init] animated:YES]; } } else { DDLogInfo(@"检查QuickSetup前置条件不满足"); [self showCommonFailedToastView]; } }]; }]; } - (void)orientationChangeAction { //横屏模式下 if (self.orientation == TPBInterfaceOrientationRight || self.orientation == TPBInterfaceOrientationLeft) { CGFloat maxBarHeight = kFlexibleBar_MinHeight + 50.0f; self.flexibleBar.frame = CGRectMake(0, 0, MAX(kScreen_Width, kScreen_Height), maxBarHeight); } //竖屏模式下 else { CGFloat maxBarHeight = kFlexibleBar_MinHeight + 50.0f; self.flexibleBar.frame = CGRectMake(0, 0, MIN(kScreen_Width, kScreen_Height), maxBarHeight); } } // MARK: 工具函数 - (BOOL)isForGateway { return [TPStandaloneClient currentInstance].discoveredDevice.isGateway; } @end
最新发布
12-06
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值