Pedro.Alonso Pedro.Alonso - 4 months ago 10x
Swift Question

iOS swift how to place an imageview in a uiview exactly

I have an issue, I'm creating an imageView programmatically and then add it to a center view, which is kind of working. But the problem is that is not taking the whole space in the center view, it appears yes in the uiview but not covering all always a bit down. Any help?

The code:

//let backgroundImage = UIImageView(frame: centerView.frame)
let backgroundImage: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.centerView.bounds.size.width, height: self.centerView.bounds.size.height))
print("backgorundImage coordinates: \(backgroundImage.frame)")
backgroundImage.image = drawOverImage
backgroundImage.sizeThatFits(CGSizeMake(centerView.bounds.width, self.centerView.bounds.height))
//check this the image is being drawn bottom because is the fame for the previous 0.0
//backgroundImage.autoPinEdgeToSuperviewMargin(ALEdge.Top, relation: NSLayoutRelation.Equal)
//backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill //too big
//backgroundImage.contentMode = UIViewContentMode.ScaleAspectFit //sama
backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill
backgroundImage.clipsToBounds = true
//imageView.image = background =

let coordinatesForImage: CGRect = self.view.convertRect(backgroundImage.frame, toView: centerView)
let pointOfImage: CGPoint = backgroundImage.convertPoint(self.centerView.frame.origin, toView: backgroundImage)

print("coordinates test: \(coordinatesForImage)")
print("point x: \(pointOfImage.x)")
print("point y: \(pointOfImage.y)")

//backgroundImage.contentMode = UIViewContentMode.ScaleToFill
self.centerView.insertSubview(backgroundImage, atIndex: 0)

let pointOfImageToSuperView: CGPoint = (backgroundImage.superview?.convertPoint(, toView: self.centerView))!

print("superview imagepoint: \(pointOfImageToSuperView)")

The comments are all the thing I'm trying to do.


Simply try:

let backgroundImage: UIImageView = UIImageView(frame: self.centerView.bounds)