Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

ios - How do I add an extra separator to the top of a UITableView?

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?

Here's the code to build the cells - it's pretty straightforward. The overall layout is handled in a 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;
}
question from:https://stackoverflow.com/questions/3012120/how-do-i-add-an-extra-separator-to-the-top-of-a-uitableview

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To replicate the standard iOS separator lines, I use a 1 px (not 1 pt) hair line tableHeaderView with the table view's 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):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...