Как добавить дополнительный разделитель в начало UITableView?
У меня есть вид для 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;
}
Ответы
Ответ 1
Чтобы реплицировать стандартные разделительные линии iOS, я использую линию волос tableHeaderView
с 1 px (не 1 pt) с табличным представлением 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;
});
То же самое в Свифт (спасибо, датчанин Джордан, Юичи Като):
let px = 1 / UIScreen.main.scale
let frame = CGRectMake(0, 0, self.tableView.frame.size.width, px)
let line = UIView(frame: frame)
self.tableView.tableHeaderView = line
line.backgroundColor = self.tableView.separatorColor
Ответ 2
Я просто получил эту проблему и понял, что разделитель сверху отображается только при прокрутке таблицы.
То, что я тогда сделал, было следующим
- В интерфейсе Builder перейдите в "Scroll View Size"
- Установите вставки содержимого сверху до 1
Альтернативно в коде вы можете сделать
[tableView setContentInset:UIEdgeInsetsMake(1.0, 0.0, 0.0, 0.0)];
ПРИМЕЧАНИЕ. Это больше не работает для iOS7, поскольку разделители больше не отображаются.
Ответ 3
У меня была такая же проблема, и я не мог найти ответ. Поэтому я добавил строку в конец моего заголовка таблицы.
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
В дополнение к Ortwin answer, если вам нужно добавить некоторый запас в верхний разделитель, чтобы он соответствовал вставке разделителя, вы должны вставить свой верхний разделитель в другое представление
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;
Надеюсь, что это поможет.
Ответ 5
Я сделал расширение 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
topSeparator.heightAnchor.constraint(equalToConstant: LayoutHelper.pixelInPoints(1)).isActive = true
topSeparator.tag = _topSeparatorTag
topSeparator.alpha = 0
superview?.setNeedsLayout()
}
} else {
_topSeparator?.removeFromSuperview()
}
}
func removeSeparatorsOfEmptyCells() {
tableFooterView = UIView(frame: .zero)
}
}
Чтобы включить его, просто вызовите tableView.showTopSeparatorWhenScrolled(true)
после того, как вы установили delegate
для своего UITableView
Ответ 6
Я решил это, добавив одну дополнительную строку в начале таблицы. Просто нужно установить его высоту в 1, установить, что текст пуст, отключить взаимодействие с пользователем для него, а во всем коде корректировать значение indexPath.row.
Ответ 7
Добавить разделитель между заголовком и первой строкой:
В поле зрения метода делегата в заголовке добавьте subview self.separator
// @свойство (неатомное, сильное) 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;
}