Sha*_*esh 80 iphone uibutton uiview ios cgrect
我有一个UIView,我在其中安排了UIButtons.我想找到那些UIButton的位置.
我知道buttons.frame会给我这些职位,但只会就其直接的超级视图给我立场.
有没有办法我们可以找到这些按钮的位置,与UIButton superview的超级视图有关?
例如,假设UIView名为"firstView".
然后,我有另一个UIView,"secondView".这个"SecondView"是"firstView"的子视图.
然后我将UIButton作为"secondView"的子视图.
->UIViewController.view
--->FirstView A
------->SecondView B
------------>Button
Run Code Online (Sandbox Code Playgroud)
现在,有没有什么方法可以找到UIButton的位置,就"firstView"而言?
mpr*_*vat 171
你可以用这个:
目标C.
CGRect frame = [firstView convertRect:buttons.frame fromView:secondView];
Run Code Online (Sandbox Code Playgroud)
迅速
let frame = firstView.convert(buttons.frame, from:secondView)
Run Code Online (Sandbox Code Playgroud)
文档参考:
https://developer.apple.com/documentation/uikit/uiview/1622498-convert
Vla*_*lad 29
虽然不是特定于层次结构中的按钮,但我发现这更易于可视化和理解:
从这里:原始来源
ObjC:
CGPoint point = [subview1 convertPoint:subview2.frame.origin toView:viewController.view];
Run Code Online (Sandbox Code Playgroud)
迅速:
let point = subview1.convert(subview2.frame.origin, to: viewControll.view)
Run Code Online (Sandbox Code Playgroud)
iAj*_*iAj 18
针对Swift 3进行了更新
if let frame = yourViewName.superview?.convert(yourViewName.frame, to: nil) {
print(frame)
}
Run Code Online (Sandbox Code Playgroud)
小智 9
用于转换子视图框架的 UIView 扩展(灵感来自 @Rexb 答案)。
extension UIView {
// there can be other views between `subview` and `self`
func getConvertedFrame(fromSubview subview: UIView) -> CGRect? {
// check if `subview` is a subview of self
guard subview.isDescendant(of: self) else {
return nil
}
var frame = subview.frame
if subview.superview == nil {
return frame
}
var superview = subview.superview
while superview != self {
frame = superview!.convert(frame, to: superview!.superview)
if superview!.superview == nil {
break
} else {
superview = superview!.superview
}
}
return superview!.convert(frame, to: self)
}
}
// usage:
let frame = firstView.getConvertedFrame(fromSubview: buttonView)
Run Code Online (Sandbox Code Playgroud)
框架:(X,Y,宽度,高度).
因此,即使超级超视图,宽度和高度也不会改变.您可以轻松获得X,Y如下.
X = button.frame.origin.x + [button superview].frame.origin.x;
Y = button.frame.origin.y + [button superview].frame.origin.y;
Run Code Online (Sandbox Code Playgroud)
如果堆叠了多个视图并且您不需要(或不想)知道您感兴趣的视图之间的任何可能的视图,您可以这样做:
static func getConvertedPoint(_ targetView: UIView, baseView: UIView)->CGPoint{
var pnt = targetView.frame.origin
if nil == targetView.superview{
return pnt
}
var superView = targetView.superview
while superView != baseView{
pnt = superView!.convert(pnt, to: superView!.superview)
if nil == superView!.superview{
break
}else{
superView = superView!.superview
}
}
return superView!.convert(pnt, to: baseView)
}
Run Code Online (Sandbox Code Playgroud)
这里targetView将是按钮,baseView将是ViewController.view。
这个函数试图做的是:
如果targetView没有超级视图,则返回它的当前坐标。
如果targetView's超级视图不是 baseView(即按钮和 之间有其他视图viewcontroller.view),则检索转换后的坐标并将其传递给下一个superview。
它通过移向 baseView 的视图堆栈继续执行相同的操作。
一旦到达baseView,它就会进行最后一次转换并返回它。
注:它不处理所处的环境targetView定位下baseView。