UITableView的一些常用设置

一:UITableViewStyle:Grouped,如果不想要header和footer,需添加以下方法

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01f;
}

二:UITableView背景颜色设置

tableView.backgroundColor = [UIColor greenColor]改变整个tableView的颜色,对于tableViewCell,我们不应该直接使用 cell.backgroundColor。Cell本身是一个UIView,我们所看到的部分其实只是它的一个Subview,也就是 cell.contentView。所以,如果直接改变cell本身的背景色,依然会被cell.contentView给覆盖,没有效果。 

   
cell.contentView.backgroundColor = [UIColor blueColor];
Cocoa提供的按钮背景色为透明。因为ContentView被移开,下面是tableView的颜色,已经不是cell的一部分了。

所以,最好的方式应该是通过cell.backgroundView来改变cell的背景。按照文档说明,backgroundView始终处于cell的最下层,所以,将cell里的其它subview背景设为[UIColor clearColor],以cell.backgroundView作为统一的背景,应该是最好的方式。

三:UITableView的分割线

UITableView的分割线(separator)是私有类,应该是无法获取的。

不过你可以通过tableView的属性修改它:

UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 20, 400, 300) style:UITableViewStylePlain];
 
    tableView.separatorColor = [UIColor redColor];
 
    tableView.separatorInset = UIEdgeInsetsMake(0,80, 0, 80);        // 设置端距,这里表示separator离左边和右边均80像素
 
    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
 
    tableView.dataSource = self;

如此设置后的tableView是这样的:(左右空出了80像素)

如果你想设置单个分割线的颜色,那就自己画分割线吧。你可以用coreGraphics,也可以用UIView,这里用UIView来画:

UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 20, 400, 300) style:UITableViewStylePlain];
 
     
 
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;   // 这样就不会显示自带的分割线
 
    tableView.dataSource = self;
 
     
 
    for (int i = 0; i < 8; i++) {
 
         
 
        UIView * separator = [[UIView alloc] initWithFrame:CGRectMake(10, (i+1) * 40 /* i乘以高度*/, 380, 1)];
 
         
 
        separator.backgroundColor = [UIColor colorWithRed:0.03 * i green:0.05*i blue:0.1*i alpha:1];
 
         
 
        [tableView addSubview:separator];
 
         
 
    }
 
     
 
    [self addSubview:tableView];

效果:

滚动正常

当然,为了和谐,你应该把自定义的separator的间隔和cell的高度设为一致。

四:tableViewCell选中时颜色:

[tableView deselectRowAtIndexPath:indexPath animated:YES];  //取消选择状态,否则一直在选中

1.系统默认的颜色设置

// 无色

cell.selectionStyle = UITableViewCellSelectionStyleNone;

// 蓝色

cell.selectionStyle = UITableViewCellSelectionStyleBlue;

// 灰色

cell.selectionStyle = UITableViewCellSelectionStyleGray;

2.自定义颜色和背景设置

UIColor *color = [[UIColoralloc]initWithRed:0.0green:0.0blue:0.0alpha:1];//通过RGB来定义自己的颜色

  1. cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];  
  2. cell.selectedBackgroundView.backgroundColor = [UIColor xxxxxx];  

3自定义UITableViewCell选中时背景

cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cellart.png"]];   

还有字体颜色 

cell.textLabel.highlightedTextColor = [UIColor xxxcolor];  [cell.textLabel setTextColor:color];//设置cell的字体的颜色 

 
 
 
原文地址:https://www.cnblogs.com/duyuiOS/p/4990718.html