iPhone - Get Position of UIView within entire UIWindow

白昼怎懂夜的黑 提交于 2019-11-26 07:53:02

问题


The position of a UIView can obviously be determined by view.center or view.frame etc. but this only returns the position of the UIView in relation to it\'s immediate superview.

I need to determine the position of the UIView in the entire 320x480 co-ordinate system. For example, if the UIView is in a UITableViewCell it\'s position within the window could change dramatically irregardless of the superview.

Any ideas if and how this is possible?

Cheers :)


回答1:


That's an easy one:

[aView convertPoint:localPosition toView:nil];

... converts a point in local coordinate space to window coordinates. You can use this method to calculate a view's origin in window space like this:

[aView.superview convertPoint:aView.frame.origin toView:nil];

2014 Edit: Looking at the popularity of Matt__C's comment it seems reasonable to point out that the coordinates...

  1. don't change when rotating the device.
  2. always have their origin in the top left corner of the unrotated screen.
  3. are window coordinates: The coordinate system ist defined by the bounds of the window. The screen's and device coordinate systems are different and should not be mixed up with window coordinates.



回答2:


Swift 4:

let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)



回答3:


In Swift:

let globalPoint = aView.superview?.convertPoint(aView.frame.origin, toView: nil)



回答4:


Swift 3, with extension:

extension UIView{
    var globalPoint :CGPoint? {
        return self.superview?.convert(self.frame.origin, to: nil)
    }

    var globalFrame :CGRect? {
        return self.superview?.convert(self.frame, to: nil)
    }
}



回答5:


Here is a combination of the answer by @Mohsenasm and a comment from @Chigo adopted to Swift

extension UIView {
    var globalFrame: CGRect? {
        let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
        return self.superview?.convert(self.frame, to: rootView)
    }
}


来源:https://stackoverflow.com/questions/1465394/iphone-get-position-of-uiview-within-entire-uiwindow

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