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

Выберите First Row по умолчанию в UITableView

У меня есть приложение, которое является viewbased, и я добавляю представление tableview в качестве представления к основному виду. Я принял UITableViewDelegate, чтобы ответить на методы таблицы. Все работает нормально, но я хочу выбрать первую строку или UITableView по умолчанию (выделено).

Пожалуйста, помогите мне, с каким кодом мне нужно и где мне нужно его поставить.

4b9b3361

Ответ 1

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

Лучший способ использовать это в своем коде, если вы хотите выбрать любую строку по умолчанию, используйте в viewDidAppear.

Ответ 2

Обновлено решение Switcher 3.0

let indexPath = IndexPath(row: 0, section: 0)
tblView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)

Ответ 3

- (void)viewWillAppear:(BOOL)animated
    {

       [super viewWillAppear:animated];

     // assuming you had the table view wired to IBOutlet myTableView

        // and that you wanted to select the first item in the first section

        [myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:0];
    }

Ответ 4

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];

    if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){
        NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
        [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
    }
}

Ответ 5

Здесь, как это сделать в Swift 1.2:

override func viewWillAppear(animated: Bool) {
    let firstIndexPath = NSIndexPath(forRow: 0, inSection: 0)
    self.tableView.selectRowAtIndexPath(firstIndexPath, animated: true, scrollPosition: .Top)
}

Ответ 6

Чтобы выбрать первую ячейку при первом загрузке таблицы, можно подумать, что при использовании viewDidLoad - это правильное место для перехода, , но, в это время выполнения таблица hasn 't загрузил его содержимое, поэтому он не будет работать (и, возможно, сбой приложения, поскольку NSIndexPath будет указывать на несуществующую ячейку).

Обходной путь заключается в использовании переменной, которая указывает, что таблица загрузилась до и выполняла соответствующую работу.

@implementation MyClass {
    BOOL _tableHasBeenShownAtLeastOnce;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _tableHasBeenShownAtLeastOnce = NO; // Only on first run
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if ( ! _tableHasBeenShownAtLeastOnce )
    {
        _tableHasBeenShownAtLeastOnce = YES;
        BOOL animationEnabledForInitialFirstRowSelect = YES; // Whether to animate the selection of the first row or not... in viewDidAppear:, it should be YES (to "smooth" it). If you use this same technique in viewWillAppear: then "YES" has no point, since the view hasn't appeared yet.
        NSIndexPath *indexPathForFirstRow = [NSIndexPath indexPathForRow:0 inSection: 0];

        [self.tableView selectRowAtIndexPath:indexPathForFirstRow animated:animationEnabledForInitialFirstRowSelect scrollPosition:UITableViewScrollPositionTop];
    }
}

/* More Objective-C... */

@end

Ответ 7

Вот мое решение для быстрого 3.0:

var selectedDefaultIndexPath = false


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if dataSource.isEmpty == false, selectedDefaultIndexPath == false {
        let indexPath = IndexPath(row: 0, section: 0)
        // if have not this, cell.backgroundView will nil.
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        // trigger delegate to do something.
        _ = tableView.delegate?.tableView?(tableView, willSelectRowAt: indexPath)
        selectedDefaultIndexPath = true
    }
}

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    let cell = tableView.cellForRow(at: indexPath)
    cell?.selectedBackgroundView?.backgroundColor = UIColor(hexString: "#F0F0F0")

    return indexPath
}

Ответ 8

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

UIImage *rowBackground;
UIImage *selectionBackground;
NSInteger sectionRows = [tableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];

if (row == 0 && row == sectionRows - 1)
{
    rowBackground = [UIImage imageNamed:@"topAndBottomRow.png"];
    selectionBackground = [UIImage imageNamed:@"topAndBottomRowSelected.png"];
}
else if (row == 0)
{
    rowBackground = [UIImage imageNamed:@"topRow.png"];
    selectionBackground = [UIImage imageNamed:@"topRowSelected.png"];
}
else if (row == sectionRows - 1)
{
    rowBackground = [UIImage imageNamed:@"bottomRow.png"];
    selectionBackground = [UIImage imageNamed:@"bottomRowSelected.png"];
}
else
{
    rowBackground = [UIImage imageNamed:@"middleRow.png"];
    selectionBackground = [UIImage imageNamed:@"middleRowSelected.png"];
}


((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;

Если вы хотите просто сделать первую ячейку, то есть в indexPath.row == 0, использовать пользовательский фон.

Это происходит от Matt Gallagher отличный сайт

Ответ 9

Вы можете сделать следующее:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSIndexPath *ip=[NSIndexPath indexPathForRow:0 inSection:0];
    [myTableView selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionBottom];
}