创建自定义UITableView分割线

8
我想要创建一个像这样的分隔线: enter image description here 你有什么关于如何实现它的想法吗?我尝试获取一条线的图像并使用UIAppearance代理对象:
[[UITableView appearanceWhenContainedIn:[MyController class], nil] setSeparatorColor:
[UIColor colorWithPatternImage:[UIImage imageNamed:@"line.png"]]];
[[UITableView appearanceWhenContainedIn:[MyController class], nil] setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];

但是,不知何故,只有黑线被渲染出来。

3个回答

9
你可以尝试以下内容:
UIView *separator = [[UIView alloc] initWithFrame:CGRectMake(0, cell.contentView.frame.size.height - 1.0, cell.contentView.frame.size.width, 1)];
separator.backgroundColor = myColor;
[cell.contentView addSubview:separator];

或者

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"separator.png"]];
   imageView.frame = CGRectMake(0, 100, 320, 1);
   [customCell.contentView addSubview:imageView];

   return customCell;
}

1
我认为你最后一行是:[cell.contentView addSubview:seperator];但无论如何它都不起作用,因为我需要一条有两种颜色的分隔线。 - Claus
如何添加一张图片? - Tarek Hallak
2
我之前为我的一个应用程序使用了这个技巧,它是一个静态的UITable,我为表格放置了一个预先设计好的背景,并移除了分隔符和单元格背景;) - Tarek Hallak
当我使用外观代理时,我只得到了一条黑线。 - Claus
如果单元格被重复使用会发生什么?难道你不应该检查分隔符视图是否已经存在吗? - Mark
显示剩余4条评论

8

@Tarek 我使用了两个你的对象来创建双线。

UIView *separator = [[UIView alloc] initWithFrame:CGRectMake(0, cell.contentView.frame.size.height - 0.5, cell.contentView.frame.size.width, 1)];
UIView *separator2 = [[UIView alloc] initWithFrame:CGRectMake(0, cell.contentView.frame.size.height - 1.0, cell.contentView.frame.size.width, 1)];
separator.backgroundColor = [UIColor darkGrayColor];
separator2.backgroundColor = [UIColor blackColor];
[cell.contentView addSubview:separator];
[cell.contentView addSubview:separator2];

看起来不错!为你点赞


1

Swift 3

viewDidLoad:

//remove default separator line
tableView.separatorStyle = .none

表格视图单元格:

class MyCustomCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()

        let separator = UIView(frame: CGRect(x: 8, y: bounds.size.height - 0.5, width: bounds.size.width - 22, height: 1))
        separator.backgroundColor = UIColor.red
        contentView.addSubview(separator)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接