以编程方式将图像位置放在按钮顶部

时间:2018-03-01 08:14:29

标签: ios swift uibutton uiimageview position

我有一个按钮,我需要在按钮操作中显示我想要的图像视图

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

现在我想将该图像放在按钮顶部,使图像的底部中心正好位于按钮的顶部中心。 (想象一下标注视图如何在地图中显示pin是位置(我的方案中的按钮),标注提醒是&#34;星巴克标注&#34;位置(我的方案中的图像) - like this < / p>

请告知我如何修改以下代码以满足要求

    //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)

1 个答案:

答案 0 :(得分:0)

我会使用imageView&#39; center属性将其正确放置:

                           // 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))