重新定位超出屏幕框架的视图

Reposition view which is going out of screen frame

我在 UIView 中有一个 imageView,它在点击该按钮时显示在该按钮的顶部。按钮的位置是动态的。

如果按钮位于屏幕的最右侧,则点击该按钮时,显示的一半视图会超出屏幕(即只显示一半)

在下面的代码中,我将视图的框架设置为等于图像的宽度和高度,imageView 的位置是(图像的中心位于按钮的顶部中心)

请告诉我如何重新定位,使视图始终在边界内。下面是我用来在按钮

顶部显示我的自定义视图的代码
       //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

计算完 imageWidthimageX 后,您可以这样检查:

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

请注意,我将 imageXlet 更改为 var