iPhone - 创建自定义UITableViewCell顶部和底部边框

Sir*_*iss 6 iphone cell uitableview

我一直在寻找,并没有找到我的答案.

我用JSON中的动态单元格填充UITableView,我试图隐藏任何额外的单元格.我在IB中关闭了分离器,当然所有的细胞分离器都消失了.如何在每个tableviewcell的底部和顶部添加一条线,以便只有具有信息的单元格显示边框?我已经导入了Quartz,并且一直在玩CALayer但是找不到解决方案.

我在这里找到了类似的问题,但唯一的答案并不是很有帮助.

这样做会有更好的,不同的方式吗?

这是我的cellForRowAtIndexPath和我的numberOfRowsInSection:

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

    // Return the number of rows in the section.
    //set equal to the information in the array

    return [_jsonDataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    //create Dictionary of data in row
    NSDictionary *jsoninfo = [_jsonDataArray objectAtIndex:indexPath.row];

    //get required keys from dictionary and assign to vairables
    NSString *title = [jsoninfo objectForKey:@"title"];
    NSString *subtitle = [jsoninfo objectForKey:@"subtitle"];
    NSURL *imageURL = [NSURL URLWithString:[jsoninfo objectForKey:@"series_image_URL"]];

    //download the images.
    NSData *imgData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *img = [[UIImage alloc] initWithData:imgData];


    //set boarder for custom cells... I need to have a border on the top and bottom of the cells I am creating so xcode does not autofill the empty space.



    //fill in text to cells
    cell.textLabel.text = title;
    cell.detailTextLabel.text = subtitle;
    cell.imageView.image = img;

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ski 24

我也认为这不是最好的主意,但如果你真的想这样做,这里的代码将实现你想要的:

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];
Run Code Online (Sandbox Code Playgroud)

将此代码放在tableView:cellForRowAtIndexPath:方法中.你最后的样子UITableView将是这样的:

与选择性边界的表视图

考虑到这对性能不是很好,特别是如果你有很多细胞.如果您有更多的数据,请参阅此SO问题以获取有关如何优化图纸的帮助.