如何在确保UIView的内容位于其框架内时向UIView添加UIview?

时间:2015-05-08 15:04:09

标签: ios swift uiview ios8 addsubview

我有一个超级视图,其中包含ImageViewtestView和一些按钮。我创建了一个UIView,其中包含ImageView2removebutton。 当我将UIView添加到UIImageView时,UIView的内容不在UIView的框架中。因此,我无法应用平移手势识别器。 我试图应用约束并更改ImageView2的框架和中心。

以下是我用来创建上述UIView的代码。如何确保UIView的框架中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 个答案:

答案 0 :(得分:2)

问题是像这样的线条没有你想象的那样:

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

视图的center位于其frame坐标中 - 它与视图在其超级视图中放置的方式有关。但是,子视图的位置必须根据其超级视图bounds来描述,而不是其frame。它的bounds内部坐标,这就是你想要的。

让我们采取最简单的案例:如何在超视图中居中子视图。这不是方法:

imageView2.center = testview.center

你看到了问题吗? testview.centertestview在其超级视图中位于的位置;它不是testview内部中心,这就是你想要的。 testview的内部中心来自bounds。这就是:

let c = CGPointMake(testview.bounds.midX, testview.bounds.midY)
imageView2.center = c