Getting a UIView's visible rectangle

房东的猫 提交于 2019-12-12 07:13:36

问题


I have a UIScrollView that contains a custom UIView. Inside the custom UIView, I'd like to know the rectangle in which it's visible (i.e. not clipped).

The quick-n-dirty solution is to have the custom UIView assume that the parent is a UIScrollView and get the content size through it, but I'm looking for a better solution that doesn't involve make such assumptions.


回答1:


This should do the trick

CGRect visibleRect = CGRectIntersection(self.frame, superview.bounds);

Use that in the UIView and it should get you the rectangle (if any) that represents the visible section of that view in it's superview (The UIScrollView). I'm assuming here that there is no view between them in the hierarchy, but if there is, fiddling the code should be trivial.

Hope I could help!




回答2:


It would help if you would give more info on what is that you are trying to accomplish.

If you want to know the size of the super view you can do this:

CGRect superFrame = [self superview].frame;



回答3:


Swift 3

extension UIView {
    var visibleRect: CGRect? {
        guard let superview = superview else { return nil }
        return frame.intersection(superview.bounds)
    }
}


来源:https://stackoverflow.com/questions/4373112/getting-a-uiviews-visible-rectangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!