Как добавить дополнительный разделитель в верхней части UITableView? - PullRequest
33 голосов
/ 10 июня 2010

У меня есть вид для iPhone, который в основном разделен на две части, с информационным дисплеем в верхней половине и UITableView для выбора действий в нижней половине. Проблема в том, что над первой ячейкой в ​​UITableView нет границы или разделителя, поэтому первый элемент в списке выглядит забавно. Как добавить дополнительный разделитель вверху таблицы, чтобы отделить его от области отображения над ней?

Вот код для создания ячеек - это довольно просто. Общий макет обрабатывается в 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 ]

58 голосов
/ 27 января 2015

Чтобы реплицировать стандартные разделительные линии 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;
});

То же самое в Swift (спасибо,Дейн Джордан, Юичи Като, Тони Мерритт):

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
14 голосов
/ 08 ноября 2012

Я только что столкнулся с этой же проблемой и понял, что разделитель сверху отображается только во время прокрутки таблицы.

Затем я сделал следующее

  1. InВ Интерфейсном Разработчике перейдите к «Размер прокрутки»
  2. Установите для вкладок содержимого Top значение 1

В качестве альтернативы в коде вы можете сделать

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

ПРИМЕЧАНИЕ: этобольше не работает для iOS7, так как разделители больше не отображаются.

11 голосов
/ 17 августа 2012

У меня была такая же проблема, и я не смог найти ответ. Поэтому я добавил строку в конец заголовка таблицы.

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 голосов
/ 16 июля 2018

Swift 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
        }()
    }
}
3 голосов
/ 10 мая 2017

Я сделал расширение UITableView, которое отображает разделитель собственного стиля поверх UITableView, а таблица прокручивается.

Here is how it looks

Вот код (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

                topSeparator.tag = _topSeparatorTag
                topSeparator.alpha = 0

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

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

Чтобы включить его, просто позвоните tableView.showTopSeparatorWhenScrolled(true) после того, как вы установили delegate для своего UITableView

2 голосов
/ 19 октября 2015

В дополнение к ответу Ортвина , если вам нужно добавить поле для верхнего разделителя, чтобы соответствовать вкладке разделителя, вам нужно встроить верхний разделитель в другое представление:

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;

Надеюсь, это поможет.

0 голосов
/ 01 апреля 2014

Добавьте разделитель между представлением заголовка и первой строкой: - Для представления заголовка в методе делегата раздела добавьте подпредставление self.separator // @ property (nonatomic, strong) UIImageView * separator;

- (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;

}
0 голосов
/ 13 февраля 2014

Я решил это, добавив одну дополнительную строку в начале таблицы.Просто установите его высоту равным 1, установите его текст пустым, отключите взаимодействие с пользователем и во всем коде отрегулируйте значение indexPath.row.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...