Как прокрутить UITableView до определенной позиции
Как я могу прокрутить ячейку таблицы в определенное положение ? У меня есть таблица, которая показывает 3 строки (по высоте). я хочу, чтобы если я нажму на 1-ю строку, чем в соответствии с высотой таблицы 1-я строка должна прокручиваться и получать новую позицию (центр) и то же самое для других строк. Я попробовал contenOffset, но не получилось..
редактировать :
короче говоря, такая вещь, как сборщик данных, когда мы выбираем любую строку в сборщике, строка прокручивается до центра.
спасибо..
7 ответов:
он должен работать с помощью
- (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;Я надеюсь, что это поможет вам
Ура
[tableview scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];это приведет ваш tableview к первой строке.
наконец-то я нашел... он будет работать хорошо, когда таблица отображается только 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]; }
использовать
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:YES];Прокручивает приемник до тех пор, пока строка, определяемая путем индекса, не окажется в определенном месте на экране.и
scrollToNearestSelectedRowAtScrollPosition:animated:прокручивает табличное представление так, чтобы выбранная строка, ближайшая к указанной позиции в табличном представлении, находилась в этой позиции.
Swift версия:
let indexPath:NSIndexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.None, animated: true)перечисление: это доступные позиции прокрутки 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() } }
стоит отметить, что если вы используете
setContentOffsetподход, это может привести к тому, что ваш вид таблицы / вид коллекции немного подскочит. Я бы честно попытался пойти по этому другому пути. Рекомендуется использовать методы делегирования представления прокрутки, которые вам предоставляются бесплатно.
просто одна строка кода:
self.tblViewMessages.scrollToRow(at: IndexPath.init(row: arrayChat.count-1, section: 0), at: .bottom, animated: isAnimeted)
Comments