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

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

Как прокрутить ячейку таблицы к определенной позиции? У меня есть таблица, которая показывает 3 строки (в зависимости от высоты). то, что я хочу, - если я нажимаю на 1-ю строку, а в соответствии с высотой стола, первая строка должна прокручиваться и получать новую позицию (в центре) и такую ​​же для других строк. Я попробовал contenOffset, но не работал.

EDITED:

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

Спасибо..

4b9b3361

Ответ 1

Наконец-то я нашел... это сработает, когда таблица отображает только 3 строки... если строки больше изменений, соответственно...

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{    
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{  
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {         
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault    
                                       reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    cell.textLabel.text =[NSString stringWithFormat:@"Hello roe no. %d",[indexPath row]];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * theCell = (UITableViewCell *)[tableView     
                                              cellForRowAtIndexPath:indexPath];

    CGPoint tableViewCenter = [tableView contentOffset];
    tableViewCenter.y += myTable.frame.size.height/2;

    [tableView setContentOffset:CGPointMake(0,theCell.center.y-65) animated:YES];
    [tableView reloadData]; 
 }

Ответ 2

он должен работать с использованием - (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated, используя его следующим образом:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[yourTableView scrollToRowAtIndexPath:indexPath 
                     atScrollPosition:UITableViewScrollPositionTop 
                             animated:YES];

atScrollPosition может принимать любое из этих значений:

typedef enum {
UITableViewScrollPositionNone,
UITableViewScrollPositionTop,
UITableViewScrollPositionMiddle,
UITableViewScrollPositionBottom
} UITableViewScrollPosition;

Надеюсь, это поможет вам.

Приветствия

Ответ 3

[tableview scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];

Это приведет к отображению таблицы в первую строку.

Ответ 4

Используйте [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:YES]; Прокручивает приемник до тех пор, пока строка, указанная указательным путем, не будет находиться в определенном месте на экране.

и

scrollToNearestSelectedRowAtScrollPosition:animated:

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

Ответ 5

Версия Swift 4.2:

let indexPath:IndexPath = IndexPath(row: 0, section: 0)
self.tableView.scrollToRow(at: indexPath, at: .none, animated: true)

Enum: Доступны следующие позиции прокрутки Tableview - здесь для справки. Вам не нужно включать этот раздел в свой код.

public enum UITableViewScrollPosition : Int {

case None
case Top
case Middle
case Bottom
}

DidSelectRow:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let theCell:UITableViewCell? = tableView.cellForRowAtIndexPath(indexPath)

    if let theCell = theCell {
        var tableViewCenter:CGPoint = tableView.contentOffset
        tableViewCenter.y += tableView.frame.size.height/2

        tableView.contentOffset = CGPointMake(0, theCell.center.y-65)
        tableView.reloadData()
    }

}

Ответ 6

Стоит отметить, что если вы используете подход setContentOffset, это может привести к небольшому скачку вида просмотра/коллекции таблиц. Я бы честно попытался пойти по этому пути. Рекомендация - использовать предоставленные вами методы делегата прокрутки.

Ответ 7

Просто одна строка кода:

self.tblViewMessages.scrollToRow(at: IndexPath.init(row: arrayChat.count-1, section: 0), at: .bottom, animated: isAnimeted)