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

问题描述 投票:1回答:1

我有一个按钮,我需要显示一个图像视图,我在下面的按钮动作中做了

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

现在我想将该图像放在按钮顶部,使图像的底部中心正好位于按钮的顶部中心。 (想象一下标注视图如何在地图中显示引脚是位置(我的方案中的按钮)和标注警报是位置的“星巴克标注”(我的方案中的图像) - like this

请咨询如何修改以下代码以满足要求

    //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)
ios swift uibutton uiimageview position
1个回答
0
投票

我会使用imageViewcenter属性来正确放置它:

                           // 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))
© www.soinside.com 2019 - 2024. All rights reserved.