我有一个 ScrollView ,我在其中加载了一个可以缩放的图像,并且可以在其中“导航”。 我正在尝试以编程方式将按钮添加到 View 中,例如 MapKit 中使用的 MKAnnotation。 这可能吗?
我使用的方法是scrollViewDidZoom
func scrollViewDidZoom(scrollView: UIScrollView) {
centerScrollViewContents()
}
函数centerScrollViewContents
所在的地方
func centerScrollViewContents() {
let boundsSize = scrollView.bounds.size
var contentFrame = imageView.frame
if contentFrame.size.width < boundsSize.width {
contentFrame.origin.x = (boundsSize.width - contentFrame.size.width) / 2
} else { contentFrame.origin.x = 0 }
if contentFrame.size.height < boundsSize.height {
contentFrame.origin.y = (boundsSize.height - contentFrame.size.height) / 2
} else { contentFrame.origin.y = 0 }
imageView.frame = contentFrame
}
我用 UITapGestureRecognizer
添加按钮/注释,实现为
let posTocco = sender.locationInView(scrollView)
println("\(posTocco), \(scrollView.zoomScale)")
var button = UIButton()
let image = UIImage(named: "arrow.png") as UIImage?
button.frame = CGRectMake(posTocco.x, posTocco.y, 30, 30)
button.setImage(image, forState: .Normal)
scrollView.addSubview(button)
当然,我需要在 tapGesture 函数之外定义按钮/注释,但我不知道如何在图像缩放中移动按钮。
有什么帮助吗?
编辑:
我部分想出了如何解决这个问题,但按钮在第一次放大/缩小时略微移动。
我创建了一个新变量,用于存储最新的 zoomValue fattoreScalaCorrente
并在 scrollViewDidZoom(scrollView:)
中我施展魔法
var newLoc = CGPoint(x: posAssolute.x * scrollView.zoomScale, y: posAssolute.y * scrollView.zoomScale)
button.frame = CGRectMake(newLoc.x, newLoc.y, button.frame.width, button.frame.height)
你知道为什么我的按钮在第一次缩放时会轻微移动吗?
编辑 2: 在给出建议后使用
button.frame = CGRectMake(newLoc.x - button.frame.width/2, newLoc.y - button.frame.height/2, button.frame.width, button.frame.height)
按钮似乎有点移动,我不明白为什么。
最佳答案
尝试替换
button.frame = CGRectMake(newLoc.x, newLoc.y, button.frame.width, button.frame.height)
与
button.frame = CGRectMake(newLoc.x - button.frame.width/2, newLoc.y - button.frame.height/2, button.frame.width, button.frame.height)
关于swift - 在 ScrollView 中向可调整大小的图像添加注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32183350/