Search code examples
iosswiftuibuttonuiimageviewposition

Place image position on top of button programatically


I have a button on tap of which I need to show an image view which I did like below in button action

    let imageName = "pointed_image.png"
    let image = UIImage(named: imageName)
    let imageView = UIImageView(image: image!)
    self.addSubview(imageView)

Now i want to position that image on top of button such that bottom center of image lies exactly on top center of button. (Imagine a callout view how it displays in map where pin is the location(button in my scenario) and callout alert is the "starbucks callout" of location (image in my scenario) - like this

Pls advice how shall i modify the below code to meet the requirement

    //Build image view
    let imageName = "pointed_image.png"
    let image = UIImage(named: imageName)
    let imageView = UIImageView(image: image!)

    //Get Button frame
    let btnFrame = self.infoButton.frame

    //position image on top of buttom
    // CODE TO MODIFY BELOW
    var imgFrame: CGRect = imageView.frame
    imgFrame.origin.x = btnFrame.origin.x + 10
    imgFrame.origin.y = btnFrame.origin.y - 10
    imageView.frame = imgFrame
    self.addSubview(imageView)

Solution

  • I would use imageView's center property to place it correctly:

                               // aligned by centers in x axis
    imageView.center = CGPoint(x: self.infoButton.center.x, 
                               // in y axis, using buttons origin and imageView's height placed right on top of the button
                               y: self.infoButton.frame.origin.y - (imageView.bounds.height / 2))