如何在UITableView的顶部添加额外的分隔符?

时间:2022-10-31 22:51:47

I have a view for the iPhone that is basically split in two, with an informational display in the top half, and a UITableView for selecting actions in the bottom half. The problem is that there is no border or separator above the first cell in the UITableView, so the first item in the list looks funny. How can I add an extra separator at the top of the table, to separate it from the display area above it?

我有一个基本上分为两部分的iPhone视图,在上半部分有一个信息显示,还有一个用于选择下半部分动作的UITableView。问题是UITableView中第一个单元格上方没有边框或分隔符,因此列表中的第一个项目看起来很有趣。如何在表格顶部添加额外的分隔符,将其与上方的显示区域分开?

Here's the code to build the cells - it's pretty straightforward. The overall layout is handled in a xib.

这是构建单元格的代码 - 它非常简单。整体布局在xib中处理。

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    switch(indexPath.row) {
        case 0: {
            cell.textLabel.text = @"Action 1";
            break;
        }
        case 1: {
            cell.textLabel.text = @"Action 2";
            break;
        }
        // etc.......
    }
    return cell;
}

8 个解决方案

#1


47  

To replicate the standard iOS separator lines, I use a 1 px (not 1 pt) hair line tableHeaderView with the table view's separatorColor:

要复制标准的iOS分隔线,我使用1 px(不是1 pt)发线tableHeaderView和表视图的separatorColor:

// in -viewDidLoad
self.tableView.tableHeaderView = ({UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 1 / UIScreen.mainScreen.scale)];
    line.backgroundColor = self.tableView.separatorColor;
    line;
});

The same in Swift (thanks, Dane Jordan, Yuichi Kato, Tony Merritt):

斯威夫特也是如此(感谢Dane Jordan,Yuichi Kato,Tony Merritt):

let px = 1 / UIScreen.main.scale
let frame = CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: px)
let line = UIView(frame: frame)
self.tableView.tableHeaderView = line
line.backgroundColor = self.tableView.separatorColor

#2


14  

I just got hit with this same problem and realised that the separator at the top is only displayed whilst scrolling the table.

我刚刚遇到同样的问题,并意识到顶部的分隔符只在滚动表格时显示。

What I then did was the following

我接下来做的是以下内容

  1. In Interface Builder go to "Scroll View Size"
  2. 在Interface Builder中,转到“滚动视图大小”
  3. Set the Content Insets of Top to 1
  4. 将Top的Content Insets设置为1

Alternatively in code you could do

或者在代码中你可以做

[tableView setContentInset:UIEdgeInsetsMake(1.0, 0.0, 0.0, 0.0)];

NOTE: This no longer works for iOS7 as the separators are no longer shown at all.

注意:这不再适用于iOS7,因为分隔符根本不再显示。

#3


11  

I had the same problem and could not find an answer. So I added a line to the bottom of my table header.

我有同样的问题,无法找到答案。所以我在表格标题的底部添加了一行。

CGRect  tableFrame = [[self view] bounds] ; 
CGFloat headerHeight = 100;        
UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableFrame.size.width, headerHeight)];
// Add stuff to my table header...

// Create separator
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, headerHeight-1, tableFrame.size.width, 1)] ;
lineView.backgroundColor = [UIColor colorWithRed:224/255.0 green:224/255.0 blue:224/255.0 alpha:1.0];
[headerView addSubview:lineView];

self.tableView.tableHeaderView = headerView;

#4


2  

In complement of Ortwin's answer, if you need to add some margin to your top separator to fit the separator inset, you have to embedded your top separator in another view :

作为Ortwin的答案的补充,如果您需要为顶部分隔符添加一些边距以适合分隔符插入,则必须将顶部分隔符嵌入另一个视图中:

UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 1 / UIScreen.mainScreen.scale)];
UIView *topSeparator = [[UIView alloc] initWithFrame:CGRectMake(self.tableView.separatorInset.left, 0, self.tableView.frame.size.width - self.tableView.separatorInset.left - self.tableView.separatorInset.right, 1 / UIScreen.mainScreen.scale)];
topSeparator.backgroundColor = self.tableView.separatorColor;
[headerView addSubview:topSeparator];
self.tableView.tableHeaderView = headerView;

Hope it helps.

希望能帮助到你。

#5


2  

I made a UITableView extension that displays a native style separator on top of the UITableView, while the table gets scrolled.

我创建了一个UITableView扩展,在UITableView上显示一个本机样式分隔符,同时滚动表。

如何在UITableView的顶部添加额外的分隔符?

Here's the code (Swift 3)

这是代码(Swift 3)

fileprivate var _topSeparatorTag = 5432 // choose unused tag

extension UITableView {

    fileprivate var _topSeparator: UIView? {
        return superview?.subviews.filter { $0.tag == _topSeparatorTag }.first
    }

    override open var contentOffset: CGPoint {
        didSet {
            guard let topSeparator = _topSeparator else { return }

            let shouldDisplaySeparator = contentOffset.y > 0

            if shouldDisplaySeparator && topSeparator.alpha == 0 {
                UIView.animate(withDuration: 0.15, animations: {
                    topSeparator.alpha = 1
                })
            } else if !shouldDisplaySeparator && topSeparator.alpha == 1 {
                UIView.animate(withDuration: 0.25, animations: {
                    topSeparator.alpha = 0
                })
            }
        }
    }

    // Adds a separator to the superview at the top of the table
    // This needs the separator insets to be set on the tableView, not the cell itself
    func showTopSeparatorWhenScrolled(_ enabled: Bool) {
        if enabled {
            if _topSeparator == nil {
                let topSeparator = UIView()
                topSeparator.backgroundColor = separatorColor?.withAlpha(newAlpha: 0.85) // because while scrolling, the other separators seem lighter
                topSeparator.translatesAutoresizingMaskIntoConstraints = false

                superview?.addSubview(topSeparator)

                topSeparator.leftAnchor.constraint(equalTo: self.leftAnchor, constant: separatorInset.left).isActive = true
                topSeparator.rightAnchor.constraint(equalTo: self.rightAnchor, constant: separatorInset.right).isActive = true
                topSeparator.topAnchor.constraint(equalTo: self.topAnchor).isActive = true

let onePixelInPoints = CGFloat(1) / UIScreen.main.scale topSeparator.heightAnchor.constraint(equalToConstant: onePixelInPoints).isActive = true

让onePixelInPoints = CGFloat(1)/ UIScreen.main.scale topSeparator.heightAnchor.constraint(equalToConstant:onePixelInPoints).isActive = true

                topSeparator.tag = _topSeparatorTag
                topSeparator.alpha = 0

                superview?.setNeedsLayout()
            }
        } else {
            _topSeparator?.removeFromSuperview()
        }
    }

    func removeSeparatorsOfEmptyCells() {
        tableFooterView = UIView(frame: .zero)
    }
}

To enable it, simply call tableView.showTopSeparatorWhenScrolled(true) after you set your delegate for your UITableView

要启用它,只需在为UITableView设置委托后调用tableView.showTopSeparatorWhenScrolled(true)

#6


0  

I solved this by adding one extra line at the beginning of the table. Just have to set its height to 1, set its the text to empty, disable user interaction for it and in the whole code adjust the indexPath.row value.

我通过在表的开头添加一行来解决这个问题。只需将其高度设置为1,将其文本设置为空,禁用用户交互,并在整个代码中调整indexPath.row值。

#7


0  

Add a separator between header view and first row :- In view for Header in section delegate method add a subview self.separator //@property (nonatomic, strong) UIImageView *separator;

在标题视图和第一行之间添加一个分隔符: - 在视图中为标题委托方法添加一个子视图self.separator // @ property(非原子,强)UIImageView *分隔符;

- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {

return 41; 
}


- (UIView *)tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section {

self.headerView = [[UIView alloc] init];
self.headerView.backgroundColor = [UIUtils colorForRGBColor:TIMESHEET_HEADERVIEW_COLOR];

self.separator = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"seperator.png"]];
self.separator.frame = CGRectMake(0,40,self.view.frame.size.width,1);
[self.headerView addSubview:self.separator];
return self.headerView;

}

#8


0  

Swift 4

斯威夫特4

extension UITableView {
    func addTableHeaderViewLine() {
        self.tableHeaderView = {
            let line = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: 1 / UIScreen.main.scale))
            line.backgroundColor = self.separatorColor
            return line
        }()
    }
}

#1


47  

To replicate the standard iOS separator lines, I use a 1 px (not 1 pt) hair line tableHeaderView with the table view's separatorColor:

要复制标准的iOS分隔线,我使用1 px(不是1 pt)发线tableHeaderView和表视图的separatorColor:

// in -viewDidLoad
self.tableView.tableHeaderView = ({UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 1 / UIScreen.mainScreen.scale)];
    line.backgroundColor = self.tableView.separatorColor;
    line;
});

The same in Swift (thanks, Dane Jordan, Yuichi Kato, Tony Merritt):

斯威夫特也是如此(感谢Dane Jordan,Yuichi Kato,Tony Merritt):

let px = 1 / UIScreen.main.scale
let frame = CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: px)
let line = UIView(frame: frame)
self.tableView.tableHeaderView = line
line.backgroundColor = self.tableView.separatorColor

#2


14  

I just got hit with this same problem and realised that the separator at the top is only displayed whilst scrolling the table.

我刚刚遇到同样的问题,并意识到顶部的分隔符只在滚动表格时显示。

What I then did was the following

我接下来做的是以下内容

  1. In Interface Builder go to "Scroll View Size"
  2. 在Interface Builder中,转到“滚动视图大小”
  3. Set the Content Insets of Top to 1
  4. 将Top的Content Insets设置为1

Alternatively in code you could do

或者在代码中你可以做

[tableView setContentInset:UIEdgeInsetsMake(1.0, 0.0, 0.0, 0.0)];

NOTE: This no longer works for iOS7 as the separators are no longer shown at all.

注意:这不再适用于iOS7,因为分隔符根本不再显示。

#3


11  

I had the same problem and could not find an answer. So I added a line to the bottom of my table header.

我有同样的问题,无法找到答案。所以我在表格标题的底部添加了一行。

CGRect  tableFrame = [[self view] bounds] ; 
CGFloat headerHeight = 100;        
UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableFrame.size.width, headerHeight)];
// Add stuff to my table header...

// Create separator
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, headerHeight-1, tableFrame.size.width, 1)] ;
lineView.backgroundColor = [UIColor colorWithRed:224/255.0 green:224/255.0 blue:224/255.0 alpha:1.0];
[headerView addSubview:lineView];

self.tableView.tableHeaderView = headerView;

#4


2  

In complement of Ortwin's answer, if you need to add some margin to your top separator to fit the separator inset, you have to embedded your top separator in another view :

作为Ortwin的答案的补充,如果您需要为顶部分隔符添加一些边距以适合分隔符插入,则必须将顶部分隔符嵌入另一个视图中:

UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 1 / UIScreen.mainScreen.scale)];
UIView *topSeparator = [[UIView alloc] initWithFrame:CGRectMake(self.tableView.separatorInset.left, 0, self.tableView.frame.size.width - self.tableView.separatorInset.left - self.tableView.separatorInset.right, 1 / UIScreen.mainScreen.scale)];
topSeparator.backgroundColor = self.tableView.separatorColor;
[headerView addSubview:topSeparator];
self.tableView.tableHeaderView = headerView;

Hope it helps.

希望能帮助到你。

#5


2  

I made a UITableView extension that displays a native style separator on top of the UITableView, while the table gets scrolled.

我创建了一个UITableView扩展,在UITableView上显示一个本机样式分隔符,同时滚动表。

如何在UITableView的顶部添加额外的分隔符?

Here's the code (Swift 3)

这是代码(Swift 3)

fileprivate var _topSeparatorTag = 5432 // choose unused tag

extension UITableView {

    fileprivate var _topSeparator: UIView? {
        return superview?.subviews.filter { $0.tag == _topSeparatorTag }.first
    }

    override open var contentOffset: CGPoint {
        didSet {
            guard let topSeparator = _topSeparator else { return }

            let shouldDisplaySeparator = contentOffset.y > 0

            if shouldDisplaySeparator && topSeparator.alpha == 0 {
                UIView.animate(withDuration: 0.15, animations: {
                    topSeparator.alpha = 1
                })
            } else if !shouldDisplaySeparator && topSeparator.alpha == 1 {
                UIView.animate(withDuration: 0.25, animations: {
                    topSeparator.alpha = 0
                })
            }
        }
    }

    // Adds a separator to the superview at the top of the table
    // This needs the separator insets to be set on the tableView, not the cell itself
    func showTopSeparatorWhenScrolled(_ enabled: Bool) {
        if enabled {
            if _topSeparator == nil {
                let topSeparator = UIView()
                topSeparator.backgroundColor = separatorColor?.withAlpha(newAlpha: 0.85) // because while scrolling, the other separators seem lighter
                topSeparator.translatesAutoresizingMaskIntoConstraints = false

                superview?.addSubview(topSeparator)

                topSeparator.leftAnchor.constraint(equalTo: self.leftAnchor, constant: separatorInset.left).isActive = true
                topSeparator.rightAnchor.constraint(equalTo: self.rightAnchor, constant: separatorInset.right).isActive = true
                topSeparator.topAnchor.constraint(equalTo: self.topAnchor).isActive = true

let onePixelInPoints = CGFloat(1) / UIScreen.main.scale topSeparator.heightAnchor.constraint(equalToConstant: onePixelInPoints).isActive = true

让onePixelInPoints = CGFloat(1)/ UIScreen.main.scale topSeparator.heightAnchor.constraint(equalToConstant:onePixelInPoints).isActive = true

                topSeparator.tag = _topSeparatorTag
                topSeparator.alpha = 0

                superview?.setNeedsLayout()
            }
        } else {
            _topSeparator?.removeFromSuperview()
        }
    }

    func removeSeparatorsOfEmptyCells() {
        tableFooterView = UIView(frame: .zero)
    }
}

To enable it, simply call tableView.showTopSeparatorWhenScrolled(true) after you set your delegate for your UITableView

要启用它,只需在为UITableView设置委托后调用tableView.showTopSeparatorWhenScrolled(true)

#6


0  

I solved this by adding one extra line at the beginning of the table. Just have to set its height to 1, set its the text to empty, disable user interaction for it and in the whole code adjust the indexPath.row value.

我通过在表的开头添加一行来解决这个问题。只需将其高度设置为1,将其文本设置为空,禁用用户交互,并在整个代码中调整indexPath.row值。

#7


0  

Add a separator between header view and first row :- In view for Header in section delegate method add a subview self.separator //@property (nonatomic, strong) UIImageView *separator;

在标题视图和第一行之间添加一个分隔符: - 在视图中为标题委托方法添加一个子视图self.separator // @ property(非原子,强)UIImageView *分隔符;

- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {

return 41; 
}


- (UIView *)tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section {

self.headerView = [[UIView alloc] init];
self.headerView.backgroundColor = [UIUtils colorForRGBColor:TIMESHEET_HEADERVIEW_COLOR];

self.separator = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"seperator.png"]];
self.separator.frame = CGRectMake(0,40,self.view.frame.size.width,1);
[self.headerView addSubview:self.separator];
return self.headerView;

}

#8


0  

Swift 4

斯威夫特4

extension UITableView {
    func addTableHeaderViewLine() {
        self.tableHeaderView = {
            let line = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: 1 / UIScreen.main.scale))
            line.backgroundColor = self.separatorColor
            return line
        }()
    }
}