How do I add a UIview to an imageView while ensuring that the contents of the UIView are inside the it's frame?

后端 未结 1 911
萌比男神i
萌比男神i 2021-01-15 19:05

I have a superview which contains a ImageView, a testView, and some buttons. I created a UIView which contains ImageView2

相关标签:
1条回答
  • 2021-01-15 19:57

    The problem is that lines like this do not do what you think:

    let rect = CGRect(x: self.imageView.center.x-30, y: self.imageView.center.y-30, width: 80, height: 80)
    // ... and ...
    imageView2.center = testview.center
    

    The center of a view is in its frame coordinates - it has to do with how the view is placed in its superview. But the position of a subview must be described in terms of its superviews bounds, not its frame. Its bounds are its internal coordinates, which is what you want.

    Let's take the simplest case: how to center a subview in a superview. This is not the way:

    imageView2.center = testview.center
    

    You see the problem? testview.center is where testview is located in its superview; it is not the internal center of testview, which is what you want. The internal center of testview comes from its bounds. This is the way:

    let c = CGPointMake(testview.bounds.midX, testview.bounds.midY)
    imageView2.center = c
    
    0 讨论(0)
提交回复
热议问题