需要在iOS中控制UITmageView在UITableView上的移动

时间:2013-06-05 21:37:09

标签: ios uitableview uibutton

我有UIImageView当前移动到用户选择的UITableView中的哪一行。此功能正常。但是,我现在想要做的是使用按钮来控制它的移动。我有两个按钮,一个用于向上行,一个用于向下行。两个按钮都有不同的标记值,但调用相同的IBAction方法。我想知道的是如何将UIImageView向上/向下移动一行?我现在有以下代码可以正常工作:

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

  [self.view bringSubviewToFront:_imageView];

    [UIView animateWithDuration:.3 animations:^{
        CGRect rect = [self.view convertRect:[tableView rectForRowAtIndexPath:indexPath] fromView:tableView];
        _imageView.frame = rect;
    }];

}

上述方法可以将UIImageView移动到用户选择的任何行。

如何修改此代码,以便每次按下向上按钮时它严格向上移动一行,每次按下向下按钮时只向下移动一行?

1 个答案:

答案 0 :(得分:1)

从NSIndexPath对象中didSelectRowAtIndexPath:方法中的最后一个选定行获取表视图单元格的indexPath。

 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

  [self.view bringSubviewToFront:_imageView];
  self.indexPath = indexPath;

    [UIView animateWithDuration:.3 animations:^{
        CGRect rect = [self.view convertRect:[tableView rectForRowAtIndexPath:indexPath] fromView:tableView];
        _imageView.frame = rect;
    }];

}

在你的按钮动作方法中处理indexPath,看看上面/下面的单元格是否在同一部分,在这种情况下增加/减少行,如果在其他部分,你可能想要计算新的indexPath。

-(IBAction)btnActn:(id)sender{
    if(btn.tag ==0){
     self.indexPath=[NSIndexPath indexPathForRow:self.indexPath.row+1 inSection:self.indexPath.section];
    //Put animation code or call animation function 
    }
}

然后使用您已经使用的相同方法获取上方或下方一个单元格的矩形,并将_imageView的位置转换为新位置。