Скрыть разделительную линию на одном UITableViewCell - PullRequest
221 голосов
/ 19 декабря 2011

Я настраиваю UITableView. Я хочу скрыть строку, разделяющую ячейку last ... я могу это сделать?

Я знаю, что могу сделать tableView.separatorStyle = UITableViewCellStyle.None, но это затронет все ячейки tableView. Я хочу, чтобы это затронуло только мою последнюю камеру.

Ответы [ 38 ]

343 голосов
/ 19 декабря 2011

в viewDidLoad, добавьте эту строку:

self.tableView.separatorColor = [UIColor clearColor];

и в cellForRowAtIndexPath:

для iOS более низких версий

if(indexPath.row != self.newCarArray.count-1){
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 44, 320, 2)];
    line.backgroundColor = [UIColor redColor];
    [cell addSubview:line];
}

для iOS 7 верхнеговерсии (включая iOS 8)

if (indexPath.row == self.newCarArray.count-1) {
    cell.separatorInset = UIEdgeInsetsMake(0.f, cell.bounds.size.width, 0.f, 0.f);
}
219 голосов
/ 17 октября 2013

Вы можете использовать следующий код:

Свифт:

if indexPath.row == {your row number} {
    cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: .greatestFiniteMagnitude)
}

или:

cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, UIScreen.main.bounds.width)

по умолчанию Маржа:

cell.separatorInset = UIEdgeInsetsMake(0, tCell.layoutMargins.left, 0, 0)

для показа разделителя сквозной

cell.separatorInset = .zero

Objective-C:

if (indexPath.row == {your row number}) {
    cell.separatorInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, CGFLOAT_MAX);
}
89 голосов
/ 29 октября 2014

Для отслеживания ответа Хирен .

в ViewDidLoad и следующей строки:

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

Или, если выпри использовании XIB или раскадровки измените « separator » на « none »:

Interface builder

И в CellForRowAtIndexPath добавьте это:

CGFloat separatorInset; // Separator x position 
CGFloat separatorHeight; 
CGFloat separatorWidth; 
CGFloat separatorY; 
UIImageView *separator;
UIColor *separatorBGColor;

separatorY      = cell.frame.size.height;
separatorHeight = (1.0 / [UIScreen mainScreen].scale);  // This assures you to have a 1px line height whatever the screen resolution
separatorWidth  = cell.frame.size.width;
separatorInset  = 15.0f;
separatorBGColor  = [UIColor colorWithRed: 204.0/255.0 green: 204.0/255.0 blue: 204.0/255.0 alpha:1.0];

separator = [[UIImageView alloc] initWithFrame:CGRectMake(separatorInset, separatorY, separatorWidth,separatorHeight)];
separator.backgroundColor = separatorBGColor;
[cell addSubView: separator];

Вот пример результата, в котором я отображаю табличное представление с динамическими ячейками (но только одно с содержимым).В результате только тот, у кого есть разделитель, а не все «фиктивные» таблицы автоматически добавляются для заполнения экрана.

enter image description here

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

РЕДАКТИРОВАТЬ: Для тех, кто не всегда читает комментарии, на самом деле есть лучший способ сделать это с помощью нескольких строк кода:

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.tableFooterView = UIView()
}
50 голосов
/ 17 сентября 2013

Если вы не хотите рисовать разделитель самостоятельно, используйте это:

  // Hide the cell separator by moving it to the far right
  cell.separatorInset = UIEdgeInsetsMake(0, 10000, 0, 0);

Этот API доступен только начиная с iOS 7.

29 голосов
/ 28 сентября 2015

моя среда разработки:

  • Xcode 7.0
  • 7A220 Swift 2.0
  • iOS 9.0

выше ответы не полностью работают дляя

после попытки мое окончательно работающее решение:

let indent_large_enought_to_hidden:CGFloat = 10000
cell.separatorInset = UIEdgeInsetsMake(0, indent_large_enought_to_hidden, 0, 0) // indent large engough for separator(including cell' content) to hidden separator
cell.indentationWidth = indent_large_enought_to_hidden * -1 // adjust the cell's content to show normally
cell.indentationLevel = 1 // must add this, otherwise default is 0, now actual indentation = indentationWidth * indentationLevel = 10000 * 1 = -10000

и эффект: enter image description here

10 голосов
/ 18 июня 2017

В Swift 3 и Swift 4 вы можете написать расширение для UITableViewCell следующим образом:

extension UITableViewCell {

  func hideSeparator() {
    self.separatorInset = UIEdgeInsets(top: 0, left: self.bounds.size.width, bottom: 0, right: 0)
  }

  func showSeparator() {
    self.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
  }
}

Затем вы можете использовать это, как показано ниже (когда ячейка является экземпляром вашей ячейки):

cell.hideSeparator()
cell.showSeparator()

Действительно лучше присвоить ширину ячейки табличного представления в виде левой вставки, а не случайное число.Потому что в некоторых размерах экрана, возможно, не сейчас, но в будущем ваши разделители все еще будут видны, потому что этого случайного числа может быть недостаточно.Кроме того, в iPad в альбомном режиме вы не можете гарантировать, что ваши разделители всегда будут невидимыми.

8 голосов
/ 30 ноября 2014

Лучшее решение для iOS 7 & 8

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    DLog(@"");
    if (cell && indexPath.row == 0 && indexPath.section == 0) {

        DLog(@"cell.bounds.size.width %f", cell.bounds.size.width);
        cell.separatorInset = UIEdgeInsetsMake(0.f, cell.bounds.size.width, 0.f, 0.0f);
    }
}

Если ваше приложение вращаемое - используйте 3000.0f для левой постоянной вставки или вычислите ее на лету.Если вы попытаетесь установить правую вставку, у вас появится видимая часть разделителя в левой части ячейки на iOS 8.

7 голосов
/ 11 сентября 2016

В вашем подклассе UITableViewCell переопределите layoutSubviews и скройте _UITableViewCellSeparatorView.Работает под iOS 10.

override func layoutSubviews() {
    super.layoutSubviews()

    subviews.forEach { (view) in
        if view.dynamicType.description() == "_UITableViewCellSeparatorView" {
            view.hidden = true
        }
    }
}
7 голосов
/ 15 ноября 2013

В iOS 7 разделитель ячеек сгруппированных стилей UITableView выглядит немного иначе. Это выглядит примерно так:

enter image description here

Я попробовал ответ Кеменарана сделать это:

cell.separatorInset = UIEdgeInsetsMake(0, 10000, 0, 0);

Однако это, похоже, не работает для меня. Я не уверен почему. Поэтому я решил использовать ответ Хирена , но с использованием UIView вместо UIImageView, и нарисовал линию в стиле iOS 7:

UIColor iOS7LineColor = [UIColor colorWithRed:0.82f green:0.82f blue:0.82f alpha:1.0f];

//First cell in a section
if (indexPath.row == 0) {

    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 1)];
    line.backgroundColor = iOS7LineColor;
    [cell addSubview:line];
    [cell bringSubviewToFront:line];

} else if (indexPath.row == [self.tableViewCellSubtitles count] - 1) {

    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(21, 0, self.view.frame.size.width, 1)];
    line.backgroundColor = iOS7LineColor;
    [cell addSubview:line];
    [cell bringSubviewToFront:line];

    UIView *lineBottom = [[UIView alloc] initWithFrame:CGRectMake(0, 43, self.view.frame.size.width, 1)];
    lineBottom.backgroundColor = iOS7LineColor;
    [cell addSubview:lineBottom];
    [cell bringSubviewToFront:lineBottom];

} else {

    //Last cell in the table view
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(21, 0, self.view.frame.size.width, 1)];
    line.backgroundColor = iOS7LineColor;
    [cell addSubview:line];
    [cell bringSubviewToFront:line];
}

Если вы используете это, убедитесь, что вы указали правильную высоту представления таблицы во втором операторе if. Надеюсь, это кому-нибудь пригодится.

5 голосов
/ 22 августа 2018

Установите separatorInset.right = .greatestFiniteMagnitude в своей ячейке.

...