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

我怕爱的太早我们不能终老 提交于 2019-12-01 09:34:10

问题


I have a superview which contains a ImageView, a testView, and some buttons. I created a UIView which contains ImageView2 and a removebutton. When I add UIView to UIImageView, the contents of UIView are not in the frame of UIView. Because of that, I cannot apply pan gesture recognizer. I have tried to apply constraints and to change the frame and centre of ImageView2.

Below is the code I am using to create the above mentioned UIView. How do I ensure that the contents of the UIView are visible in the frame of the UIView?

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

testview = UIView(frame: rect)
testview.layer.cornerRadius = testview.frame.width/2
testview.backgroundColor = UIColor.blackColor()
testview.clipsToBounds = true

imageView2 = UIImageView(frame: CGRect(x: testview.frame.minX+10, y: testview.frame.minY+10, width: 60, height: 60))

let rect2 = CGRect(x: self.testview.frame.maxX-17, y: self.testview.frame.minY, width: 20, height: 20)

removeButton = UIButton(frame: rect2)

removeButton.layer.cornerRadius = removeButton.frame.width/2

removeButton.backgroundColor = UIColor.blackColor()

removeButton.clipsToBounds = true

imageView2.layer.cornerRadius = imageView2.frame.width/2

imageView2.userInteractionEnabled = true

imageView2.clipsToBounds = true
testview.alpha = 0.3

imageView2.center = testview.center

imageView2.center = testview.center

testview.addSubview(imageView2)

testview.addSubview(removeButton)

testview.bringSubviewToFront(imageView2)

imageView.addSubview(testview)

回答1:


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


来源:https://stackoverflow.com/questions/30127032/how-do-i-add-a-uiview-to-an-imageview-while-ensuring-that-the-contents-of-the-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!