Search code examples
iosswiftframecgrectbounds

Reposition view which is going out of screen frame


I have a imageView inside a UIView which displays on top of button when that button is tapped. The position of the button is dynamic.

If the button is on the extreme right of the screen, on tap of that button, half of the view which displays is going out of screen (i.e., only half is displayed)

In the code below, I'm setting my view's frame equal to image width and its height, imageView's position is (center of image is on top center of button )

Pls advice how i can reposition the such that the view will always inside the bounds. Below is the code Im using to display my custom view on top of button

       //calculate frame for view
        let imageHeight = myImage.size.height
        let imageWidth = myImage.size.width
        let imageX = myButton.minX - 
           ((myView.myImageView.bounds.width)/2) + 15
        let imageY = currentCellRect.minY - 
            (myView.myImageView.bounds.height) + 15
        let imageFrame = CGRect(x: imageX, y: imageY, width: 
             imageWidth, height: imageHeight)

        //Assign calculated from to the tool tip view
        toolTipView.frame = imageFrame

Solution

  • After calculating imageWidth and imageX you could make a check like this:

    [...]
    var imageX = myButton.minX - 
               ((myView.myImageView.bounds.width)/2) + 15
    imageX = min(imageX, view.frame.width - imageWidth)
    [...]
    

    Notice that i changed imageX from let to var.