How to get the frame of a view inside another view?

后端 未结 4 2015
攒了一身酷
攒了一身酷 2020-12-04 16:38

I have an UIImageView in the self.view (the main View) and inside it there is a UIButton. I want to know what\'s the frame of UI

相关标签:
4条回答
  • 2020-12-04 17:08

    I guess you are looking for this method

    – convertRect:toView:

    // Swift
    let frame = imageView.convert(button.frame, to: self.view)
    
    // Objective-C
    CGRect frame = [imageView convertRect:button.frame toView:self.view];
    
    0 讨论(0)
  • 2020-12-04 17:15

    Something like this? might be totally wrong, dint really thinkt it through ;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);
    

    I don't know if theres any easier way.

    0 讨论(0)
  • 2020-12-04 17:20

    There are four UIView methods which can help you, converting CGPoints and CGRects from one UIView coordinate reference to another:

    – convertPoint:toView:
    – convertPoint:fromView:
    – convertRect:toView:
    – convertRect:fromView:
    

    so you can try

    CGRect f = [imageView convertRect:button.frame toView:self.view];
    

    or

    CGRect f = [self.view convertRect:button.frame fromView:imageView];
    
    0 讨论(0)
  • 2020-12-04 17:28

    Swift 3

    You can convert the button's frame to the view's coordinate system with this:

    self.view.convert(myButton.frame, from: myButton.superview)


    Make sure to put your logic inside viewDidLayoutSubviews and not viewDidLoad. Geometry related operations should be performed after subviews are laid out, otherwise they may not work properly.

    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)
        }
    }
    

    You can just reference myButton.superview instead of myImageView when converting the frame.


    Here are more options for converting a CGPoint or 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)
    

    See the Apple Developer Docs for more on converting a CGPoint or CGRect.

    0 讨论(0)
提交回复
热议问题