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

Первоначально выбран UITableViewCell

Привет, у меня есть ситуация, когда в приложении для iPad в моем master controller есть список, а в контроллере деталей есть его детали, типичный шаблон UISplitViewController. Чего я хочу добиться, так это того, чтобы сначала была выбрана моя первая строка, а позже я хочу предоставить выбор пользователю. Я использую ячейку setSelected и в методе didSelectRowAtIndexPath удаление выделения, как это.

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSIndexPath* path = [NSIndexPath indexPathForRow:0 inSection:0];
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:path];
    [cell setSelected:NO];
} 

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

4b9b3361

Ответ 1

попробуйте это

NSIndexPath* selectedCellIndexPath= [NSIndexPath indexPathForRow:0 inSection:0];
[self tableView:tableViewList didSelectRowAtIndexPath:selectedCellIndexPath];
[tableViewList selectRowAtIndexPath:selectedCellIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];

ИЛИ

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (/* should be selected */) {
        [cell setSelected:YES animated:NO];
    }
}

Версия Swift 4 -

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    func shouldSelect() -> Bool {
        // Some checks
    }
    if shouldSelect() {
            tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    }
}

Ответ 2

Чтобы ячейка была выбрана, вы должны вызвать -setSelected:animated: из -tableView:willDisplayCell:forRowAtIndexPath: следующим образом:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (/* should be selected */) {
        [cell setSelected:YES animated:NO];
    }
}

Вызов -setSelected из другого места не имеет эффекта.

Ответ 3

Swift 4: выбор ячейки изначально

import UIKit

class MyViewController: UIViewController, UITableViewDelegate {
    @IBOutlet weak var tableView: UITableView!
    ...

     func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

        if /* your code here */ == indexPath.row {
            tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableView.ScrollPosition.none)
        }
    }

    ...
}

Ответ 4

Я не знаю, что вы ожидаете ответа. По умолчанию, если вы хотите выбрать первую строку в таблицеView без ручного выбора, просто запустите метод didSelectRowAtIndexPath, подобный этому

- (void)viewDidAppear:(BOOL)animated {
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [myTableView selectRowAtIndexPath:indexPath animated:YES  scrollPosition:UITableViewScrollPositionBottom];
}

Ответ 5

Это также поможет в случае POP-навигации

.h файл,

NSIndexPath *defaultSelectedCell

.m Файл

Поместите этот код в ViewDidLoad

defaultSelectedCell= [NSIndexPath indexPathForRow:0 inSection:0];

в viewDidAppear

[self.tableView selectRowAtIndexPath:defaultSelectedCell animated:NO  scrollPosition:UITableViewScrollPositionNone];

Это поможет, когда вы выполните POP, введите этот код в viewWillAppear

[self.catTableView selectRowAtIndexPath:defaultSelectedCell animated:NO scrollPosition:UITableViewScrollPositionNone];

в tableView didSelectRowAtIndexPath Метод,

defaultSelectedCell = [NSIndexPath indexPathForRow:indexPath.row inSection:0];

Это помогает мне в полной мере либо загружать первый раз, либо Pop Navigation.

Ответ 6

Swift 4 и 5: выбор ячеек изначально только один раз без willDisplayCell сбрасывающего их статус:

override func viewWillAppear(_ animated: Bool) {
    for section in 0..<tableView.numberOfSections {
        for row in 0..<tableView.numberOfRows(inSection: section) {
            let indexPath = IndexPath(row: row, section: section)

            if /* your condition for selecting here */ {
                _ = tableView.delegate?.tableView?(tableView, willSelectRowAt: indexPath) // remove if you don't want to inform the delegate
                tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
                tableView.delegate?.tableView?(tableView, didSelectRowAt: indexPath) // remove if you don't want to inform the delegate
            }
        }
    }
}

Ответ 7

Лучший вариант

Swift 5

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if shouldSelectThisRow {
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    } else {
        tableView.deselectRow(at: indexPath, animated: false)
    }
}

Ответ 8

Swift 5, спасибо @Ravindhiran много отвечаю:

let selectedCellIndexPath = IndexPath(row: 0, section: 0)
tableView(tableViewList, didSelectRowAt: selectedCellIndexPath)
tableViewList.selectRow(at: selectedCellIndexPath, animated: false, scrollPosition: .none)

или же

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if /* should be selected */{
          cell.setSelected(true, animated: false)
     }
}

Ответ 9

 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        // reset cell state
        cell.accessoryType = .none  // (if you needed)
        tableView.deselectRow(at: indexPath, animated: false)

        // if need select
        cell.accessoryType = .checkmark // (if you needed)
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    }

// method work fine when tap cell 
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)

use [cell setSelected: YES animated: NO]; нажатие на ячейку didSelectRowAt, didDeselectRowAt не работает