iPhone - Create custom UITableViewCell top and bottom borders

放肆的年华 提交于 2019-12-02 18:38:05
Marko Nikolovski

I also think it's not the best idea, but if you really want to do this, here's code that will achieve what you want:

tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

// Draw top border only on first cell
if (indexPath.row == 0) {
    UIView *topLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 1)];
    topLineView.backgroundColor = [UIColor grayColor];
    [cell.contentView addSubview:topLineView];
}

UIView *bottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.bounds.size.height, self.view.bounds.size.width, 1)];
bottomLineView.backgroundColor = [UIColor grayColor];
[cell.contentView addSubview:bottomLineView];

Put this code in the tableView:cellForRowAtIndexPath: method. The final look of your UITableView will be like this:

Take into account that this is not very good for performance, especially if you have a lot of cells. If you have a bigger amount of data, refer to this SO question for help on how to optimize the drawing.

seufagner

Only try this at tableView:cellForRowAtIndexPath: method

[cell.contentView.layer setBorderColor:[UIColor grayColor].CGColor];
[cell.contentView.layer setBorderWidth:1.0f];

It sounds like a sub-optimal solution to try to "distinguish" your valid cells from empty ones with lines. A superior approach would be to clean up the data source before populating the table with it.

Use Custom Cells. Your Datasoure (Models) should drive the information into the Custom Cells. Create a setter within the Custom Cell class that can be set at each row. as in....


  1. Allocation your Custom Cell with reuse Id,

  2. Pass the property that is determing if the line should show:
    [cell setCustomLines:Model.property];

  3. return the cell;


You will have far more flexibility to design the CustomCell any way you want, Images, Lines, Colors, or other ways of letting your user's see a difference among your cells.

Technically, Marco's Answer will work, and good job on a simple solution. But you will not be able to expand this very much farther this this.

wrtsprt

This is not the answer to the question, but the clean solution for the original problem.

Add an empty UIView as the footer of the UITableView. Then the empty cells will be hidden. See this answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!