向 UITableViewCell 添加分隔符

Adding a separator to UITableViewCell

我正在构建一个应用程序 (iOS 8.0),而我有一个使用 AutoLayout 和故事板构建的 UITableViewControlled。 tableView设置为static & grouped,tableView分隔符设置为none.

我正在尝试使用此代码(在 viewWillAppear: 中调用)为另外两个单元格添加分隔符,但由于某种原因,它没有显示:

        // Create a separator for the tableView cells
    UIView *separatorViewTop = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 1.0f, self.fromCell.frame.size.width, 1.0f)];
    UIView *separatorViewBottom = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 43.0f, self.fromCell.frame.size.width, 1.0f)];
    separatorViewTop.backgroundColor = [UIColor grayColor];
    separatorViewBottom.backgroundColor = [UIColor grayColor];

    // Add it
    [self.fromCell.contentView addSubview:separatorViewTop];
    [self.toCell.contentView addSubview:separatorViewBottom];

fromCell 和 toCell 并在 IB 中与 IBOutlets 连接。

可以请人看一下吗? 谢谢!

如果您将 XIB 用于自定义单元格,那么在 XIB 本身中添加这些分隔符视图会很容易。我认为与在 运行 时间添加相比,它更灵活。

您还可以创建一个高度为 1 像素的 UIView,并使用您想要的分隔符背景颜色

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath
{
    //Your code to create the tableviewcell...
    //Below 'theCell' is the current cell at index path to return

    if (thisIsTheCellIWantToAddSeparator) {
        UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, theCell.frame.size.height-1, theCell.frame.size.width, 1)];
        theCell.backgroundColor = YOURCOLOR; //Set the color you want
        [theCell.contentView addSubview:imgView];
    }
    return  theCell;
}