在超级视图中使用convertRect获取相对位置

3

我有一堆水平的UITableView放在一个UIViewController1中。我想找到被点击的UITableViewCell的位置,我想要以UIViewController1为参考系获取位置。所以这是我在didSelectRowAtIndexPath中所做的:

MyCell *cell = (MyCell *)[tableView cellForRowAtIndexPath:indexPath];

                UIView *animatedView = [[UIView alloc] initWithFrame:cell.frame];
 [animatedView setFrame:[animatedView convertRect:animatedView.frame toView:self.newsRackController.view]];

然而,似乎这样并不能正确转换它。我做错了什么?

请查看此答案:https://dev59.com/lXRB5IYBdhLWcg3wNk93#4620507。 - KDaker
2个回答

8

你需要将UITableViewCell的CGRect从UITableView的视图中转换,然后再次将其转换为你的视图控制器的视图。

但是,也许你可以直接使用UITableView的方法。

- (CGRect)rectForRowAtIndexPath:(NSIndexPath *)indexPath

获取此CGRect并将其转换为您的UIViewController的视图。

谢谢,非常好的答案! - Fede Cugliandolo
对我来说,这个解决方案没有考虑到contentOffset或contentInset。 - Ben Clayton

1

这是因为 animatedView 不属于任何父级,而你正在使用 frame 作为 bounds。你应该先找到框架,然后相应地初始化 animatedView

MyCell *cell = (MyCell *)[tableView cellForRowAtIndexPath:indexPath];
CGRect animatedViewFrame = [tableView convertRect:cell.frame toView:self.newsRackController.view];
UIView *animatedView = [[UIView alloc] initWithFrame:animatedViewFrame];

谢谢!这实际上是对问题的答案。 - skywinder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接