iPhone - Get Position of UIView within entire UIWindow

后端 未结 6 1413
长发绾君心
长发绾君心 2020-11-27 09:14

The position of a UIView can obviously be determined by view.center or view.frame etc. but this only returns the position of the

6条回答
  •  猫巷女王i
    2020-11-27 10:01

    For me this code worked best:

    private func getCoordinate(_ view: UIView) -> CGPoint {
        var x = view.frame.origin.x
        var y = view.frame.origin.y
        var oldView = view
    
        while let superView = oldView.superview {
            x += superView.frame.origin.x
            y += superView.frame.origin.y
            if superView.next is UIViewController {
                break //superView is the rootView of a UIViewController
            }
            oldView = superView
        }
    
        return CGPoint(x: x, y: y)
    }
    

提交回复
热议问题