Подтвердить что ты не робот

Есть ли способ удалить разделительную линию из одной ячейки в UITableView?

Я знаю, что я могу изменить свойство separatorStyle UITableView на UITableViewCellSeparatorStyleNone или UITableViewCellSeparatorStyleSingleLine, чтобы изменить все ячейки в TableView так или иначе.

Мне интересно иметь некоторые ячейки с SingleLine Separator и некоторые ячейки без. Возможно ли это?

4b9b3361

Ответ 1

Лучше всего настроить таблицу separatorStyle на UITableViewCellSeparatorStyleNone и вручную добавить/вычертить строку (возможно, в tableView:cellForRowAtIndexPath:), когда захотите.

Ответ 2

Следуя совету Майка, вот что я сделал.

В tableView: cellForRowAtIndexPath:

...
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    // Drawing our own separatorLine here because I need to turn it off for the
    // last row. I can only do that on the tableView and on on specific cells.
    // The y position below has to be 1 less than the cell height to keep it from
    // disappearing when the tableView is scrolled.
    UIImageView *separatorLine = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, cell.frame.size.height - 1.0f, cell.frame.size.width, 1.0f)];
    separatorLine.image = [[UIImage imageNamed:@"grayDot"] stretchableImageWithLeftCapWidth:1 topCapHeight:0];
    separatorLine.tag = 4;

    [cell.contentView addSubview:separatorLine];

    [separatorLine release];
}

// Setup default cell setttings.
...
UIImageView *separatorLine = (UIImageView *)[cell viewWithTag:4];
separatorLine.hidden = NO;
...
// In the cell I want to hide the line, I just hide it.
seperatorLine.hidden = YES;
...

В viewDidLoad:

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; 

Ответ 3

Это хорошо работает для меня.

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

Все это вставляет вставки влево и вправо от линии до мертвой точки, что составляет 160, что делает ее невидимой.

Затем вы можете контролировать, какие ячейки применять его с помощью indexPath.row;

Ответ 4

self.separatorInset = UIEdgeInsetsMake(0, CGRectGetWidth(self.frame)/2, 0, CGRectGetWidth(self.frame)/2);

Ответ 5

Мне удалось скрыть разделительную линию для нескольких разных ячеек, сделав левую вставку размером всей ширины границ ячейки. Замените "indexPath.row == 0" номером строки, который нужно удалить с разделительной строки.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];


if (indexPath.row == 0 || indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 8 || indexPath.row == 9) {
    cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0);
}
else {
    cell.separatorInset = UIEdgeInsetsMake(0, 24, 0, 0);
}


return cell;
}

Ответ 6

Для людей с тем же вопросом, которые используют swift и хотят скрыть разделительную линию только для определенного типа ячейки, способ сделать это следующий:

 override func layoutSubviews() {
    super.layoutSubviews()
    subviews.forEach { (view) in
        if view.dynamicType.description() == "_UITableViewCellSeparatorView" {
            view.hidden = true
        }
    }
}

Ответ 7

Лучший способ добиться этого - отключить разделители строк по умолчанию, подкласс UITableViewCell и добавить собственный разделитель строк в качестве поднабора contentView - см. ниже пользовательскую ячейку, которая используется для представления объекта типа SNStock, который имеет два строковых свойства, ticker и name:

import UIKit

private let kSNStockCellCellHeight: CGFloat = 65.0
private let kSNStockCellCellLineSeparatorHorizontalPaddingRatio: CGFloat = 0.03
private let kSNStockCellCellLineSeparatorBackgroundColorAlpha: CGFloat = 0.3
private let kSNStockCellCellLineSeparatorHeight: CGFloat = 1

class SNStockCell: UITableViewCell {

  private let primaryTextColor: UIColor
  private let secondaryTextColor: UIColor

  private let customLineSeparatorView: UIView

  var showsCustomLineSeparator: Bool {
    get {
      return !customLineSeparatorView.hidden
    }
    set(showsCustomLineSeparator) {
      customLineSeparatorView.hidden = !showsCustomLineSeparator
    }
  }

  var customLineSeparatorColor: UIColor? {
   get {
     return customLineSeparatorView.backgroundColor
   }
   set(customLineSeparatorColor) {
     customLineSeparatorView.backgroundColor = customLineSeparatorColor?.colorWithAlphaComponent(kSNStockCellCellLineSeparatorBackgroundColorAlpha)
    }
  }

  required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  init(reuseIdentifier: String, primaryTextColor: UIColor, secondaryTextColor: UIColor) {
    self.primaryTextColor = primaryTextColor
    self.secondaryTextColor = secondaryTextColor
    self.customLineSeparatorView = UIView(frame:CGRectZero)
    super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier:reuseIdentifier)
    selectionStyle = UITableViewCellSelectionStyle.None
    backgroundColor = UIColor.clearColor()

    contentView.addSubview(customLineSeparatorView)
    customLineSeparatorView.hidden = true
  }

  override func prepareForReuse() {
    super.prepareForReuse()
    self.showsCustomLineSeparator = false
  }

  // MARK: Layout

  override func layoutSubviews() {
    super.layoutSubviews()
    layoutCustomLineSeparator()
  }

  private func layoutCustomLineSeparator() {
    let horizontalPadding: CGFloat = bounds.width * kSNStockCellCellLineSeparatorHorizontalPaddingRatio
    let lineSeparatorWidth: CGFloat = bounds.width - horizontalPadding * 2;
    customLineSeparatorView.frame = CGRectMake(horizontalPadding,
      kSNStockCellCellHeight - kSNStockCellCellLineSeparatorHeight,
      lineSeparatorWidth,
      kSNStockCellCellLineSeparatorHeight)
  }

  // MARK: Public Class API

  class func cellHeight() -> CGFloat {
    return kSNStockCellCellHeight
  }

  // MARK: Public API

  func configureWithStock(stock: SNStock) {
    textLabel!.text = stock.ticker as String
    textLabel!.textColor = primaryTextColor
    detailTextLabel!.text = stock.name as String
    detailTextLabel!.textColor = secondaryTextColor
    setNeedsLayout()
  } 
}

Чтобы отключить использование разделителя строк по умолчанию, tableView.separatorStyle = UITableViewCellSeparatorStyle.None;. Сторона потребителя относительно проста, см. Пример ниже:

private func stockCell(tableView: UITableView, indexPath:NSIndexPath) -> UITableViewCell {
  var cell : SNStockCell? = tableView.dequeueReusableCellWithIdentifier(stockCellReuseIdentifier) as? SNStockCell
  if (cell == nil) {
    cell = SNStockCell(reuseIdentifier:stockCellReuseIdentifier, primaryTextColor:primaryTextColor, secondaryTextColor:secondaryTextColor)
  }
  cell!.configureWithStock(stockAtIndexPath(indexPath))
  cell!.showsCustomLineSeparator = true
  cell!.customLineSeparatorColor = tintColor
  return cell!
}