Есть ли способ удалить разделительную линию из одной ячейки в UITableView? - PullRequest
12 голосов
/ 31 июля 2009

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

Мне интересно иметь несколько ячеек с разделителем SingleLine и несколько ячеек без. Это возможно?

Ответы [ 7 ]

16 голосов
/ 31 июля 2009

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

9 голосов
/ 20 июня 2010

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

В табличном представлении: 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; 
6 голосов
/ 16 сентября 2014

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

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

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

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

5 голосов
/ 01 ноября 2014
self.separatorInset = UIEdgeInsetsMake(0, CGRectGetWidth(self.frame)/2, 0, CGRectGetWidth(self.frame)/2);
2 голосов
/ 12 февраля 2016

Мне удалось скрыть разделительную линию для нескольких разных ячеек, сделав в левой вставке размер всей ширины границ ячейки. Замените "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;
}
1 голос
/ 05 января 2017

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

 override func layoutSubviews() {
    super.layoutSubviews()
    subviews.forEach { (view) in
        if view.dynamicType.description() == "_UITableViewCellSeparatorView" {
            view.hidden = true
        }
    }
}
0 голосов
/ 26 апреля 2015

Лучший способ добиться этого - отключить разделители строк по умолчанию, подкласс 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!
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...