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

Как установить полную ширину разделителя в UITableView

Итак, у меня есть UITableView, где разделители не имеют полной ширины. Он заканчивается как 10 пикселей перед левой стороной. Я играл с этим кодом в viewDidLoad

self.tableView.layoutMargins = UIEdgeInsetsZero;

также в раскадровке, когда вы можете выбрать пользовательские или стандартные селектора. Теперь все заполненные ячейки не имеют селекторов полной ширины, но ячейки, которые пусты, имеют полную ширину.

Как я могу это исправить?

Спасибо за помощь

4b9b3361

Ответ 1

Хорошо, я нашел ответ. Не знаю, почему я не сталкивался с этим постом раньше, но, конечно же, после того, как вы разместите вопрос, вдруг перед вами появится нужное сообщение. Я получил ответ из этого поста: iOS 8 UITableView разделитель 0 не работает

Просто добавьте этот код на ваш TableViewController

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

Ответ 2

Это работало для меня на устройствах iOS 8.4-9.0 с использованием Xcode 6.4 и Swift 1.2:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = UITableViewCell()


    cell.preservesSuperviewLayoutMargins = false
    cell.separatorInset = UIEdgeInsetsZero
    cell.layoutMargins = UIEdgeInsetsZero

    return cell
}

Swift 3.0 Обновление

cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero

Ответ 3

В вашем UITableViewCell

Перейдите к Инспектору Атрибутов в Интерфейсном Разработчике и просто измените "15" на 0. Сделайте это для всех ячеек, которые вы хотите изменить.

instets

Вам может понадобиться добавить [cell setLayoutMargins:UIEdgeInsetsZero]; к вашей tableViewCell

Ответ 4

Я наследую от UITableViewController и вам необходимо добавить дополнительные настройки в две настройки в willDisplayCell, чтобы установить preservesSuperviewLayoutMargins в значение false. В Swift это выглядит так:

override func tableView(_tableView: UITableView,
    willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath) {

        if cell.respondsToSelector("setSeparatorInset:") {
            cell.separatorInset = UIEdgeInsetsZero
        }
        if cell.respondsToSelector("setLayoutMargins:") {
            cell.layoutMargins = UIEdgeInsetsZero
        }
        if cell.respondsToSelector("setPreservesSuperviewLayoutMargins:") {
            cell.preservesSuperviewLayoutMargins = false
        }
}

Ответ 5

  • Выберите UITableViewCell
  • Перейдите в Инспектор атрибутов
  • Перейдите в Separator и измените его на "пользовательские вставки"
  • Установите поля left и/или right. (По умолчанию left: 15, right: 0)

Посмотрите, как это работает для меня (используя left: 100):

введите описание изображения здесь

Результат:

введите описание изображения здесь

Ответ 6

для Swift 3:

override func viewDidLoad() {
  super.viewDidLoad()

  tableView.separatorInset = .zero
  tableView.layoutMargins = .zero
}

Ответ 7

Для людей, имеющих проблемы с iPad, это приведет вас в состояние, аналогичное iPhone. Затем вы можете отрегулировать параметр separatorInset.

tableView.cellLayoutMarginsFollowReadableWidth = false

Ответ 8

Протестировано для iOS 9.3 и Swift 2.2. Обязательно поместите код в willDisplayCell, который вызывается непосредственно перед отображением ячейки, а не в cellForRowAtIndexPath, где вы создаете только ячейку.

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.separatorInset = UIEdgeInsetsZero
    cell.layoutMargins = UIEdgeInsetsZero
}

Добавьте override в функцию для UITableViewController, например: override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

Ответ 9

для быстрого в iOS 9+

если используется пользовательский UITableViewCell:

override var layoutMargins: UIEdgeInsets {
    get { return UIEdgeInsetsZero }
    set(newVal) {}
}

тогда для вашего tableView в viewDidLoad:

    self.tableView?.separatorInset = UIEdgeInsetsZero;
    self.tableView?.layoutMargins = UIEdgeInsetsZero;

Ответ 10

Используйте его в методе cellForRowAtIndexPath, чтобы настроить спецификации разделителя ячеек,
он отлично работает на iOS9. 0+

 cell.separatorInset = UIEdgeInsetsZero;
 cell.layoutMargins = UIEdgeInsetsZero;
 cell.preservesSuperviewLayoutMargins = NO;

Ответ 11

Ничто из вышеперечисленного не работает для меня в Swift 2.2 и Xcode 7.3.1

Оказалось, самое простое решение из всех. Код не нужен. Просто измените значения TableViewCell макета TableViewCell в инспекторе UITableView:

Ответ 12

Для Swift 3:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
            cell.separatorInset = UIEdgeInsets.zero
        }
        if cell.responds(to: #selector(setter: UITableViewCell.layoutMargins)) {
            cell.layoutMargins = UIEdgeInsets.zero
        }
        if cell.responds(to: #selector(setter: UITableViewCell.preservesSuperviewLayoutMargins)) {
            cell.preservesSuperviewLayoutMargins = false
        }
    }

Ответ 13

Ни одно из этих решений не работает на iPad, но я предложил решение, которое охватывает оба устройства:

С многоразовыми ячейками:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    ...[other code]...
    [cell setLayoutMargins:UIEdgeInsetsZero];
    [cell setSeparatorInset:UIEdgeInsetsZero];
    return cell;
}

С одноразовыми ячейками:

- (void)removeSeparatorInset:(UITableView*)tableView{
    NSArray *cells = [tableView visibleCells];
    for (UITableViewCell *cell in cells){
        [cell setLayoutMargins:UIEdgeInsetsZero];
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

-(void) viewDidLayoutSubviews{
   [super viewDidLayoutSubviews];
   [self removeSeparatorInset:self.tableView];
}

Просто чтобы расширить этот подход:

@property(nonatomic) UIEdgeInsets separatorInset;
@property(nonatomic) UIEdgeInsets layoutMargins;

Оба свойства могут использоваться UITableView & UITableViewCell. Последний, по сути, является свойством UIView, который является родительским классом UITableView и UITableViewCell.

Ответ 14

В viewDidLoad (проверено iOS11 - swift 4.1)

пытаться

tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)

Ответ 15

По умолчанию Inset разделителя равна 15 слева. Измените параметр Inset Separator Inset с auto на custom и установите для inset значение 0.

enter image description here