0

I have an UIToolbar with several UIBarButtonItems. I'm currently trying to implement a custom animation for which I need a starting point. This animation is triggered with click on one of the toolbar's items, namely plusIcon.

The animation works, but I haven't been able to get a CGPoint for the UIBarButtonItem.

Browsing the web I found the following for a navigationBar (unfortunately in Objective-C):

- (void)handleItemPressed {
UIView *targetView = nil;
for (UIView *subView in self.navigationController.navigationBar.subviews) {
    if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
        for (UILabel *label in subView.subviews) {
            if ([label isKindOfClass:[UILabel class]]) {
                if ([label.text isEqualToString:"right"]) {
                    targetView = subView;
                    break;
                }
            }
        }
    }
}

CGRect rect = [targetView convertRect:targetView.frame toView:self.view];
CGPoint center_you_need = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
}

I tried to convert this code for my desires, but I don't think this suits my problem - if it does, please correct me.

I've also tried the following, to get to the position of iconPlus:

btnPos = CGPoint(x: toolbar.center.x + (toolbar.center.x / 2) + (toolbar.center.x / 6), y: toolbar.center.y + 5)

This one works, but only on the iPhone X - on other devices, toolbar.center somehow won't return the actual center of the toolbar.

Any suggestion, any ideas how to get a UIBarButtonsItem's position?

Tom
  • 167
  • 9
  • Add target to button with passing sender object, `btn.addTarget(self, #selector(handlePress(_:))` then inside action event method print what you need. `print(sender.frame).. etc. – Coder ACJHP May 19 '19 at 20:25
  • The center of the toolbar is where it is centered in its superview, not its internal center. – matt May 19 '19 at 20:39
  • You cannot get the position of a bar button item, as it is not a view. Use a bar button item with a custom view so that you have a view to work with. – matt May 19 '19 at 20:43
  • @matt I tried, but changing device the `.center` seems to be different. – Tom May 19 '19 at 21:01
  • You can convert button frame with view like ` let convertToWindow = subview.convert(subview.bounds, to: window)` – Coder ACJHP May 19 '19 at 22:05
  • https://www.hackingwithswift.com/example-code/uikit/how-to-convert-a-cgpoint-in-one-uiview-to-another-view-using-convert – Coder ACJHP May 19 '19 at 22:08

0 Answers0