【问题标题】:Scrollview only zooms to upper left cornerScrollview 只缩放到左上角
【发布时间】:2017-06-02 00:32:19
【问题描述】:

我以编程方式创建了一个滚动视图并添加了一个图像作为它的子视图,但是当我尝试放大图像时,它只会放大到上角并且它不允许我滚动查看图像的不同部分。

这是我用来创建滚动视图的代码:

let scrollView = UIScrollView()

var image: NSData!

override func viewDidLoad() {
    super.viewDidLoad()

    scrollView.minimumZoomScale = 1.0
    scrollView.maximumZoomScale = 3.0
    scrollView.zoomScale = 1.0
    scrollView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
    scrollView.delegate = self
    scrollView.isPagingEnabled = false
    scrollView.contentSize = CGSize(width: self.view.frame.width, height: self.view.frame.height)

    view.addSubview(scrollView)

    scrollView.addSubview(imageView)

    imageView.image = UIImage(data: image as Data)
    imageView.contentMode = .scaleAspectFit
    imageView.isUserInteractionEnabled = true

    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(share))
    longPress.minimumPressDuration = 0.5
    longPress.numberOfTapsRequired = 0
    imageView.addGestureRecognizer(longPress)

    let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(recognizer:)))
    doubleTap.numberOfTapsRequired = 2
    scrollView.addGestureRecognizer(doubleTap)

}

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return imageView
}

func share(sender: UILongPressGestureRecognizer) {
    if sender.state == .ended {
        if UIImage(data: image as Data) != nil {
            let Item = UIImage(data: self.image! as Data)
            let activity = UIActivityViewController(activityItems: [Item!], applicationActivities: nil)
            activity.excludedActivityTypes = [UIActivityType.print, UIActivityType.addToReadingList, UIActivityType.openInIBooks]
            self.present(activity, animated: true, completion: nil)
        }
    }
}

func handleDoubleTap(recognizer: UITapGestureRecognizer) {
    if scrollView.zoomScale > scrollView.minimumZoomScale {
        scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)
    } else {
        scrollView.setZoomScale(scrollView.maximumZoomScale, animated: true)
    }
}

非常感谢您的任何帮助

【问题讨论】:

标签: ios swift xcode image uiscrollview


【解决方案1】:

当您设置滚动视图的缩放比例时,问题出在您的代码中。您没有指定它应该缩放到的位置。所以很自然地,它会缩放并停留在左上角。

您需要在handleDoubleTap(recognizer: UITapGestureRecognizer) 中获取触摸位置,计算缩放矩形,然后在滚动视图上调用scrollRectToVisible

【讨论】:

  • handleDoubleTap 仅用于当用户双击它会放大或缩小时。但是当我用手指放大时,它也只是放大到左上角。
  • 您使用的是自动布局还是约束?
  • 是的,我对滚动视图中的 imageView 使用了约束
  • 如果你使用约束,那么它会带回左上角。不要使用约束。
  • 感谢您对我的帮助。我还以编程方式创建了图像视图。
猜你喜欢
  • 1970-01-01
  • 2014-07-04
  • 1970-01-01
  • 2017-08-16
  • 1970-01-01
  • 1970-01-01
  • 2011-12-02
  • 2017-11-12
  • 2019-05-24
相关资源
最近更新 更多