我有一个按钮,我需要显示一个图像视图,我在下面的按钮动作中做了
let imageName = "pointed_image.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
self.addSubview(imageView)
现在我想将该图像放在按钮顶部,使图像的底部中心正好位于按钮的顶部中心。 (想象一下标注视图如何在地图中显示引脚是位置(我的方案中的按钮)和标注警报是位置的“星巴克标注”(我的方案中的图像) -
请咨询如何修改以下代码以满足要求
//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)
我会使用imageView
的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))