【发布时间】:2011-12-26 07:38:42
【问题描述】:
我在self.view(主视图)中有一个UIImageView,里面有一个UIButton。我想知道self.view而不是UIImageView中UIButton的框架是什么。
【问题讨论】:
标签: ios objective-c xcode uiimageview frame
我在self.view(主视图)中有一个UIImageView,里面有一个UIButton。我想知道self.view而不是UIImageView中UIButton的框架是什么。
【问题讨论】:
标签: ios objective-c xcode uiimageview frame
我猜你正在寻找这个方法
// Swift
let frame = imageView.convert(button.frame, to: self.view)
// Objective-C
CGRect frame = [imageView convertRect:button.frame toView:self.view];
【讨论】:
有四种UIView 方法可以帮助您,将CGPoints 和CGRects 从一个UIView 坐标引用转换为另一个:
– convertPoint:toView:
– convertPoint:fromView:
– convertRect:toView:
– convertRect:fromView:
你可以试试
CGRect f = [imageView convertRect:button.frame toView:self.view];
或
CGRect f = [self.view convertRect:button.frame fromView:imageView];
【讨论】:
斯威夫特 3
您可以使用以下方法将按钮的框架转换为视图的坐标系:
self.view.convert(myButton.frame, from: myButton.superview)
确保将您的逻辑放入 viewDidLayoutSubviews 而不是 viewDidLoad。几何相关的操作需要在子视图布局后进行,否则可能无法正常工作。
class ViewController: UIViewController {
@IBOutlet weak var myImageView: UIImageView!
@IBOutlet weak var myButton: UIButton!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let buttonFrame = self.view.convert(myButton.frame, from: myButton.superview)
}
}
在转换帧时,您可以只引用myButton.superview 而不是myImageView。
这里有更多用于转换 CGPoint 或 CGRect 的选项。
self.view.convert(point: CGPoint, from: UICoordinateSpace)
self.view.convert(point: CGPoint, from: UIView)
self.view.convert(rect: CGRect, from: UICoordinateSpace)
self.view.convert(rect: CGRect, from: UIView)
self.view.convert(point: CGPoint, to: UICoordinateSpace)
self.view.convert(point: CGPoint, to: UIView)
self.view.convert(rect: CGRect, to: UICoordinateSpace)
self.view.convert(rect: CGRect, to: UIView)
有关转换CGPoint 或CGRect 的更多信息,请参阅Apple Developer Docs。
【讨论】:
这样的?可能完全错了,我真的想透了;p
CGRect frame = CGRectMake((self.view.frame.origin.x-imageview.frame.origin.x) +btn.frame.origin.x,
(self.view.frame.origin.y.imageview.frame.origin.y)+btn.frame.origin.y,
btn.frame.size.width,
btn.frame.size.height);
不知道有没有更简单的方法。
【讨论】: