Search code examples
swiftxcodelayoutuitapgesturerecognizerscreen-size

How to get exactly the same point on different screen sizes?


I want to call the action (go to another view) when user tap specific area of image (black dots): . Image fills whole view, content mode is 'Aspect Fit'. The problem is that when I setup it on one screen size (e.g. iPhone 8) on another the 'tap area' is shifted. I've tried to solve this with button and constraints or UITapGestureRecognizer with point conversion using screen resolution (nativeBounds), but nothing helps.


Solution

  • It is possible to use constraints to match the positions of the circles with UIButtons. The trick is to use the multiplier of the constraint to scale the buttons width/height and position to the screen size.

    I'll describe how to do it for one button, and then you can repeat it for the others. I assume the image is 657 wide by 918 high. If I have the dimensions reversed, you'll need to substitute the actual values for the ones I have used.

    1. Create a UIView to hold the image and buttons. Give this view an aspect ratio constraint with multiplier 657:918 which is width:height. Add the UIImageView to this view and constrain its 4 edges to the edges of the view with 0 offsets. Give this view constraints to the left and right edges of the main view and give it a vertical constraint to place it on the screen.
    2. Get the width/height of the circle in the image and the horizontal and vertical positions of the right edge and bottom edge. For example, the topmost circle is 106 x 106 and ends at horizontal position 392 and the bottom is at 338.
    3. Set the width of the button equal to the width of the containing view with multiplier 106:657 which is width of circle:width of the image.
    4. Set the height of the button equal to the height of the containing view with multiplier 106:918 which is height of circle:height of the image.
    5. Set the trailing edge of the button equal to the trailing edge of the containing view with multiplier 392:657 which is end of circle:width of image.
    6. Set the bottom edge of the button equal to the bottom edge of the containing view with multiplier 338:918 which is bottom of circle:height of the image.

    This will allow the button to stay aligned with the circle on all devices. Repeat steps 2 through 6 for the other circles.