2017-06-02 6 views
0

プログラムでスクロールビューを作成し、その画像をサブビューとして追加しましたが、画像を拡大しようとすると上隅にズームされてスクロールできません画像のさまざまな部分を参照してください。Scrollviewのみ左上隅にズームします

ここで私はscrollviewを作成するために使用するコードです:

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

はあなたのscrollViewのzoomscaleを設定する際に問題があなたのコードにあるヘルプ

+0

imageviewフレームはどこですか? – Daniel

+0

あなたの質問ごとに私の答えを確認してくださいhttps://stackoverflow.com/questions/43624834/uiimageview-zoom-and-pinch-in-uiscrollview/43626273#43626273 –

答えて

1

の任意の種類いただき、誠にありがとうございます。ズームする場所は指定しないでください。自然に、ズームインして左上隅にとどまります。

handleDoubleTap(recognizer: UITapGestureRecognizer)にタッチの位置を取得し、ズームのためにrectを計算し、スクロールビューでscrollRectToVisibleを呼び出す必要があります。

+0

handleDoubleTapは、ユーザーがダブルタップそれがズームインまたはズームアウトされます。しかし、それはまた、単に私の指でズームインすると、左上隅にズームするだけです。 –

+0

オートレイアウトまたは制約を使用していますか? –

+0

はいスクロールビューにあるimageViewに制約を使用しました –

関連する問題