1.我想做一个动画,需要知道rightBarButtonItem对应self.view中的位置,即:
CGPoint toPoint = [self.navigationController.navigationBar convertPoint:self.navigationItem.titleView.center toView:self.view];
但是获取到的位置坐标始终不正确:
2.问题是:
怎么能够获取到导航栏中的各个navigationItem对应在self.view中的位置呢?
迷茫2017-04-18 09:07:01
self.view 是一個放到navigation controller 裡的view, navigation bar 也一樣, 所以它倆之間是平級的, 並不是說navigation bar 是self.view 的子view,自然也就沒有辦法計算navigation bar裡的子項目在self.view 裡的位置。
我想你想算的應該是 item 在 window 或在 navigationController.view 中的位置吧?
你可以用 view debugging 看一下各個 view 之間的層級關係。
PHPz2017-04-18 09:07:01
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 就是你需要的
迷茫2017-04-18 09:07:01
經過檢驗發現:
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上卻不正確呢?