首页 > ios:如何获取导航栏中rightBarButtonItem对应self.view的坐标?

ios:如何获取导航栏中rightBarButtonItem对应self.view的坐标?

1.我想做一个动画,需要知道rightBarButtonItem对应self.view中的位置,即:

CGPoint toPoint = [self.navigationController.navigationBar convertPoint:self.navigationItem.titleView.center toView:self.view];

但是获取到的位置坐标始终不正确:

2.问题是:
怎么能够获取到导航栏中的各个navigationItem对应在self.view中的位置呢?


UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
[btn setTitle:@"right" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];

CGRect frameInNaviView = [self.navigationController.view convertRect:btn.frame fromView:btn.superview];

UIView *vShow = [[UIView alloc] initWithFrame:frameInNaviView];
vShow.backgroundColor = [UIColor redColor];
[self.navigationController.view addSubview:vShow];

frameInNaviView 就是你需要的


经过测试发现:

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
[btn setTitle:@"right" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];

CGRect frameInNaviView = [self.navigationController.view convertRect:btn.frame fromView:btn.superview];

这样确实是可以获取到正确的位置;但由于在ipad上测试发现,同样的代码,得到的结果却是{{0, 0}, {44, 44}}.这貌似又引出了一个新的问题:为何在iPhone 上是正确的,在ipad上却不正确呢?


self.view 是一個放到 navigation controller 里的 view, navigation bar 也一樣, 所以它倆之間是平級的, 並不是說 navigation bar 是 self.view 的子 view,自然也就沒有辦法計算 navigation bar 里的子項目在 self.view 里的位置。

我想你想算的應該是 item 在 window 或者在 navigationController.view 中的位置吧?

你可以用 view debugging 看一下各個 view 之間的層級關係。

【热门文章】
【热门文章】