Получить позицию UITableviewCell из «видимой» области или окна - PullRequest
23 голосов
/ 08 мая 2011

Я создаю базу приложений для iPhone на uitableview и uitabbar. В каждой ячейке таблицы есть кнопка «Добавить в избранное». Когда я нажал эту кнопку, я хочу, чтобы ячейка «перепрыгнула» с ее позиции на любимый элемент панели вкладок (аналогично эффекту загрузки в installous)

Эффект работает хорошо, если я нахожусь в верхней 10 ячейке, но если я прокручиваю в tableView, эффект не хорош, потому что начальная позиция рассчитывается по размеру uitableview.

Можно узнать положение ячейки по видимой области.

Например: для сороковой позиции ячейки есть x: 0, y: 1600, w: 320, y: 50, я хочу, чтобы позиция была сверху, а не сверху uiview, поэтому что-то вроде этого x: 0, у: 230, вес: 320, у: 50

Ответы [ 3 ]

77 голосов
/ 08 мая 2011

Да, вы можете использовать rectForRowAtIndexPath:, вам просто нужно будет указать indexPath строки, по которой вы щелкнули.

rectForRowAtIndexPath:

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

...

РЕДАКТИРОВАТЬ

Преобразование:

CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]]; 
0 голосов
/ 29 марта 2012

Да, это возможно вот так

-(void)click:(id)sender
{
    int clickcelltag;
    clickcelltag=sender.tag;

    NSIndexPath *index =[NSIndexPath indexPathForRow:clickcelltag inSection:0];

    [userreviewtblview scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];//userreviewtblview is a UITableView name
}

Надеюсь, это поможет вам: -)

0 голосов
/ 08 мая 2011

Итак, вот код, который я использовал: (он может быть оптимизирован, я уверен):

Сначала добавьте свойство NSindexPath ** в свою ячейку.
* Реализуйте это в вашем контроллере таблицы: *

-(void)addCellToFavorisWithAnimation:(ResultSearchOffreCell*)cell{
/* Generate image from cell
----------------------------------------------------------*/
UIGraphicsBeginImageContextWithOptions(cell.bounds.size, cell.opaque, [[UIScreen mainScreen] scale]);
[cell.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// Launch first animation (go to top-right)
//----------------------------------------------------------*/
CGRect rectInTableView = [self.tableView rectForRowAtIndexPath:cell.indexPath];
CGRect rectInSuperview = [self.tableView convertRect:rectInTableView toView:[self.tableView superview]];

cellAnimationContainer = [[UIImageView alloc] initWithFrame:rectInSuperview];

[cellAnimationContainer setFrame:CGRectMake(cellAnimationContainer.frame.origin.x, cellAnimationContainer.frame.origin.y+50 , cellAnimationContainer.frame.size.width, cellAnimationContainer.frame.size.height)];

[cellAnimationContainer setImage:img];

AppDelegate_Shared *appDelegate = [UIApplication sharedApplication].delegate;
[appDelegate.window addSubview:cellAnimationContainer];
[UIView beginAnimations:@"addFavorite-Step1" context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[UIView setAnimationDuration:0.2];
[cellAnimationContainer setFrame:CGRectMake(20,cellAnimationContainer.frame.origin.y-10, cellAnimationContainer.frame.size.width, cellAnimationContainer.frame.size.height)];
[cellAnimationContainer setAlpha:0.7];
[UIView commitAnimations];
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{


/* Launch second animation => go to favoris Tab and remove from self.view
 ---------------------------------------------------------------------------*/
if([anim isEqual:@"addFavorite-Step1"])
{
    [UIView beginAnimations:@"addFavorite-Step2" context:nil]; 
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDelegate:self]; 
    [cellAnimationContainer setAlpha:0.4];
    [cellAnimationContainer setFrame:CGRectMake(150, 420, 20, 20)];
    [UIView commitAnimations];
}
else if([anim isEqual:@"addFavorite-Step2"])
{
    [cellAnimationContainer removeFromSuperview];
    [cellAnimationContainer release];         
}
}
...