UITableView 的几种常见控件参数变更写法(截止 -2016 年 10 月 26 日)

本贴最后更新于 1700 天前,其中的信息可能已经事过境迁


UITableView 是 IOS 开发中几乎都会用到的,通常我们会对其中的一些参数进行自定义设定,下面列举常用的一些用法

首先做好准备工作,写好带有 navigation 和 tableview 的页面并且在 cell 中填入数据,tableview 的类型先选择默认,cell 的类型也选择默认。
完整代码入下:

ViewController.m

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UITableView * mainTableView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _mainTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _mainTableView.dataSource = self;
    _mainTableView.delegate = self;
    [self.view addSubview:_mainTableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * ID = @"myCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"第%ld组,第%ld行",(long)indexPath.section,(long)indexPath.row];
    return cell;
}
@end

实际效果:
这里写图片描述

1.去掉多余的 cell:

在 viewdidload 中添加如下代码:

_mainTableView.tableFooterView = [[UIView alloc]init];

实际效果:
这里写图片描述

2.去掉所有 cell 的分割线

在 viewdidload 中添加如下代码:

//设置分割线类型为无类型
_mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

或:

//设置分割线颜色为无色
_mainTableView.separatorColor = [UIColor clearColor];

或在-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 中添加如下代码:

   //cell的边框颜色设置为白色,边框宽度为2
   cell.layer.borderColor = [[UIColor whiteColor]CGColor];
   cell.layer.borderWidth = 2;

注意:*若要去掉部分 cell 分割线,只需要判断一下 cell 的位置即可,如:

    if (indexPath.row == 2) {
        cell.layer.borderColor = [[UIColor whiteColor]CGColor];
        cell.layer.borderWidth = 2;
    }

去掉部分 cell 分割线实际效果:
这里写图片描述

去掉所有 cell 分割线实际效果:
这里写图片描述

3.禁止选中整个 tableview:

若想让添加在 tableview 上的子控件都不可选择,可在 viewdidload 中添加如下代码:

_mainTableView.allowsSelection = NO;

演示效果:
这里写图片描述

4.禁止选中某一行 cell:

若想单纯的禁止选中 cell 而 tableview 上其他子控件不受影响,则在-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 中添加如下代码:

cell.selectionStyle = UITableViewCellSelectionStyleNone;

若想禁止具体某一行的 cell,则只需定位到具体的 cell 行数即可:

if (indexPath.row == 2) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

演示样例:
这里写图片描述

5.cell 分割线靠左(IOS10 下全部有效):

默认的 cell 分割线是不靠左的,想要靠左则需要添加如下代码:

方法一:
在 viewdidload 中添加如下代码,也是最简单的写法,但是在之前的版本上可能无效:

_mainTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);

或者:

_mainTableView.separatorInset = UIEdgeInsetsZero;

方法二:

-(void)viewDidLayoutSubviews
{
    if ([_mainTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_mainTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([_mainTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_mainTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

方法三:
直接在 viewdidload 中添加如下代码(旧设备可能无效):

    if ([_mainTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_mainTableView setSeparatorInset:UIEdgeInsetsZero];
    }
        
    if ([_mainTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_mainTableView setLayoutMargins:UIEdgeInsetsZero];
    }


方法四:
直接在-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 中添加如下代码(旧设备可能无效):

    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }


演示效果:
这里写图片描述

6.点击 cell 时选中效果慢慢恢复:

在 cell 点击事件方法中添加[tableView deselectRowAtIndexPath:indexPath animated:YES],完整代码如下:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

效果对比:
这里写图片描述 这里写图片描述

7.添加 cell 右侧指示器:

在-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 中天下如下代码:

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

实际效果:
这里写图片描述

#8.cell 的侧滑菜单(自定义)

-(NSArray <UITableViewRowAction *>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewRowAction* deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *_Nonnull action,NSIndexPath * _Nonnull indexPath)
                                          {
                                              [_mainTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                                              _mainTableView.editing = NO;
                                          }];
    
    UITableViewRowAction* editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"编辑" handler:^(UITableViewRowAction *_Nonnull action,NSIndexPath * _Nonnull indexPath)
                                          {
                                              [_mainTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                                              _mainTableView.editing = NO;
                                          }];
    editAction.backgroundColor = [UIColor orangeColor];
    
    return @[deleteAction,editAction];
}

实际效果:
这里写图片描述

**注意:**若想在不同的 cell 上显示不同的侧滑菜单,则需要加上 row 的判断即可,代码如下:

	if (indexPath.row == 2) {
              return @[deleteAction];
        }

实例效果:
这里写图片描述

9.系统自带 cell 侧滑删除按钮:

系统默认自带侧滑的菜单中只有删除功能,代码如下:

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//实现方法
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击了删除按钮");
    UILabel * v = [[UILabel alloc]initWithFrame:CGRectMake(50, 350, self.view.bounds.size.width-100, 40)];
    v.backgroundColor = [UIColor greenColor];
    v.text = @"点击了删除按钮";
    [self.view addSubview:v];
}

实际效果
这里写图片描述

10.长按 cell 自定义弹框:

在-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 中给 cell 添加长按手势:

UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
    [cell addGestureRecognizer:longPress];

实现方法:

-(void)longPress:(UILongPressGestureRecognizer *)recognizer
{
    if (recognizer.state == UIGestureRecognizerStateBegan) {
    //这里的UItableviewcell可以换成你自定义的cell
        UITableViewCell * cell = (UITableViewCell *)recognizer.view;
        [cell becomeFirstResponder];
        
//        获取row的位置
        CGPoint point = [recognizer locationInView:_mainTableView];
        NSIndexPath * path = [_mainTableView indexPathForRowAtPoint:point];
        NSInteger row = [path row];
        NSLog(@"此时row的值为%ld",(long)row);
        UIMenuItem * copy1 = [[UIMenuItem alloc]initWithTitle:@"复制" action:@selector(copy1:)];
        UIMenuItem * transmit = [[UIMenuItem alloc]initWithTitle:@"转发" action:@selector(transmit:)];
        UIMenuItem * widthdraw = [[UIMenuItem alloc]initWithTitle:@"撤回" action:@selector(widthdraw:)];
        
        UIMenuController * menu = [UIMenuController sharedMenuController];      
        [menu setMenuItems:[NSArray arrayWithObjects:copy1,transmit,widthdraw, nil]];      
        [menu setTargetRect:cell.frame inView:cell.superview];
        [menu setMenuVisible:YES animated:YES];
    }
}

//让长按成为第一响应,不写的话,长按cell没反应
-(BOOL)canBecomeFirstResponder
{
    return YES;
}

//实现方法
-(void)copy1:(id)sender
{
    NSLog(@"点击了复制");
}

-(void)transmit:(id)sender
{
    NSLog(@"点击了转发");
}

-(void)widthdraw:(id)sender
{
    NSLog(@"点击了撤回");
}

效果演示
这里写图片描述 这里写图片描述

**注意:**细心的朋友可能看到了我在写复制的时候,定义的变量名不是 copy 而是 copy1,为何呢,因为 IOS 本身自带 copy 的相关方法,所以在写这些代码的时候,copy 的相关实现方法是可以自动提示出来的,因此我们常见的长按某项文字弹出的菜单,只要是有 copy 打头的,基本都是用的系统自带的,如果我写的是 copy,那么英文的 copy 和中文的复制会一同出现

这里写图片描述

这里写图片描述

11.自定义 cell 的高度

cell 的默认高度为 44,我们也可以自定义 cell 的高度或者规定某一行的 cell 的固定高度,比如定义所有 cell 的高度为 100:
方法一:

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

方法二:
在 viewdidload 中添加如下代码:

_mainTableView.rowHeight = 100;

演示效果:
这里写图片描述

**注意:**以上两种方法仅针对改变所有 cell 高度,两个方法若同时写,则以方法二代码为准。

若要制定某一行 cell 的高度,则需要加判断即可:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
            return 50;
            break;
            case 1:
            return 60;
            break;
        default:
            return 100;
            break;
    }
    
}

演示效果:
这里写图片描述

12.设置 cell 中的数据:

UITableViewCellStyle 有四种类型,分别是:

UITableViewCellStyleDefault,	
// Simple cell with text label and optional image view (behavior of UITableViewCell in iPhoneOS 2.x)
UITableViewCellStyleValue1,	
// Left aligned label on left and right aligned label on right with blue text (Used in Settings)
UITableViewCellStyleValue2,		
// Right aligned label on left with blue text and left aligned label on right (Used in Phone/Contacts)
UITableViewCellStyleSubtitle
// Left aligned label on top and left aligned label on bottom with gray text (Used in iPod).
    
分别解释为:
UITableViewCellStyleDefault-简单的单元格具有文本标签和可选图像视图
UITableViewCellStyleValue1-左边左对齐的标签和右边右对齐带有蓝色文本的标签
UITableViewCellStyleValue2-左边右对齐带有蓝色的标签和右边左对齐的标签
UITableViewCellStyleSubtitle-顶部左对齐的标签和底部左对齐的带有灰色文本的标签

为了对比明显我把代码整合在了一起,完整代码如下:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * ID = @"myCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {    
    switch (indexPath.row) {
        case 0:
        {
            cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            cell.backgroundColor = [UIColor yellowColor];
            cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        }
            break;
        
            break;
        case 1:
        {
            cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
            cell.backgroundColor = [UIColor blueColor];
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        }
            break;
        case 2:
        {
            cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:ID];
            cell.backgroundColor = [UIColor purpleColor];
            cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        }
            break;
            
        case 3:
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
            cell.backgroundColor = [UIColor redColor];
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
        }
    }
    cell.imageView.image = [UIImage imageNamed:@"image.jpg"];
    cell.detailTextLabel.text = @"detailTextLabel";
    cell.textLabel.text = @"textLabel";
    }
    return cell;
    }

**注意:**系统自带的 cell 中的 UIImageView 是默认置顶和置底的,若想做成类似个人头像的那种 cell 布局必须自定义 cell 才可以!

演示效果如下:
这里写图片描述

13.cell 点击跳转页面:

参见:http://blog.csdn.net/qq_15139603/article/details/52912399

  • iOS

    iOS 是由苹果公司开发的移动操作系统,最早于 2007 年 1 月 9 日的 Macworld 大会上公布这个系统,最初是设计给 iPhone 使用的,后来陆续套用到 iPod touch、iPad 以及 Apple TV 等产品上。iOS 与苹果的 Mac OS X 操作系统一样,属于类 Unix 的商业操作系统。

    84 引用 • 139 回帖
  • Objective-C
    3 引用 • 9 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • foxmailhe

    这里有一个关于 UITableView 的例子可以参考。