简体   繁体   English

在UIScrollview Swift中旋转UIView

[英]Rotating UIView in UIScrollview Swift

When I rotate the view in the scrollview it moves out of the scrollview and disappears completely after some rotation/zoom gestures. 当我在滚动视图中旋转视图时,它会移出滚动视图,并在一些旋转/缩放手势后完全消失。 It works fine as long as the zoom scale is 1. What do I have to do with my code to avoid this? 只要缩放比例为1,它就可以正常工作。为了避免这种情况,我应该如何处理我的代码?

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

    let scrollView = UIScrollView(frame: UIScreen.mainScreen().bounds)
    let rotationView = UIView()


    override func viewDidLoad() {
        super.viewDidLoad()

            let imageView = UIImageView()
                view.addSubview(scrollView)

                scrollView.delegate = self
                scrollView.minimumZoomScale = 0.5
                scrollView.maximumZoomScale = 2

                let mapImage = UIImage(named: "BMS2_300.jpg")

                imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size:mapImage!.size)
                imageView.image = mapImage

                let rotationViewframe = CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)
                rotationView.frame = rotationViewframe

                rotationView.addSubview(imageView)
                //rotationView.sizeToFit()

                scrollView.addSubview(rotationView)
                scrollView.contentSize = CGSize(width: rotationView.bounds.width, height: rotationView.bounds.height)
                scrollView.bringSubviewToFront(rotationView)
                scrollView.contentOffset = CGPoint(x: rotationView.frame.width/2, y: rotationView.frame.height/2)

            let mapRotGestureRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(ViewController.rotateMap(_:)))
                rotationView.addGestureRecognizer(mapRotGestureRecognizer)

    }

    func rotateMap(sender: UIRotationGestureRecognizer) {
        let radians = sender.rotation

        if let senderView = sender.view {
            senderView.transform = CGAffineTransformRotate(senderView.transform, radians)
            sender.rotation = 0
        }

    }


    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return self.rotationView
    }

    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        scrollView.contentSize = rotationView.frame.size
    }

解决方案是在scrollview下添加一个额外的uiview,因此新的holderView是scrollview的子视图,rotatonView是holderView的子视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM