Выберите первую строку по умолчанию в UITableView - PullRequest
54 голосов
/ 28 апреля 2010

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

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

Ответы [ 10 ]

110 голосов
/ 31 мая 2011
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [myTableView selectRowAtIndexPath:indexPath animated:YES  scrollPosition:UITableViewScrollPositionBottom];
}

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

9 голосов
/ 14 ноября 2016

Swit 3.0 обновленное решение

let indexPath = IndexPath(row: 0, section: 0)
tblView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
8 голосов
/ 05 января 2012
- (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];
    }
5 голосов
/ 03 марта 2014
- (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];
    }
}
3 голосов
/ 14 августа 2015

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

override func viewWillAppear(animated: Bool) {
    let firstIndexPath = NSIndexPath(forRow: 0, inSection: 0)
    self.tableView.selectRowAtIndexPath(firstIndexPath, animated: true, scrollPosition: .Top)
}
2 голосов
/ 21 мая 2018

Обновление Swift 4:

func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let indexPath = IndexPath(row: 0, section: 0)
    myTableView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
}

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

1 голос
/ 29 мая 2017

Вот мое решение для swift 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
}
1 голос
/ 05 октября 2015

Чтобы выбрать первую ячейку только при первой загрузке таблицы, можно подумать, что использование viewDidLoad - правильное место, , но , в этот момент выполнения таблица не имела 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
0 голосов
/ 20 июля 2010

Вы можете сделать так:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSIndexPath *ip=[NSIndexPath indexPathForRow:0 inSection:0];
    [myTableView selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionBottom];
}
0 голосов
/ 29 апреля 2010

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

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, использовать собственный фон.

Это происходит от превосходного сайта Мэтта Галлахера

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...