记录用户上次图片操作位置和缩放比, 下次进来直接展示上次退出的位置

需求: 图片可以缩放,可滚动. 并且第二次进来的时候. 直接展示上次退出界面时候的图片大小和位置

解决思路: uiscrollView + 偏好缓存(或者fmdb, 缓存方式自己选择). 

直接上代码

 

import UIKit

 

class test2: UIViewController, UIScrollViewDelegate {

    

    override func viewWillAppear(_ animated: Bool) {

        super.viewWillAppear(animated)

        print(UIApplication.shared.windows.count)

    }

    private lazy var scrollV: UIScrollView = {

        let v = UIScrollView(frame: CGRect(x: 100, y: 100, width: 300, height: 300))

        v.maximumZoomScale = 3

        v.minimumZoomScale = 1

        v.backgroundColor = .red

        v.delegate = self

        return v

    }()

    

    private lazy var imageV: UIImageView = {

        let v = UIImageView(frame: CGRect(x: 100, y: 100, width: 300, height: 300))

        v.image =  imageLiteral(resourceName: "1242-2208.png")

        return v

    }()

    

    override func viewDidLoad() {

        super.viewDidLoad()

        view.backgroundColor = .yellow

        view.addSubview(scrollV)

        scrollV.addSubview(imageV)

    }

    

    override func viewDidAppear(_ animated: Bool) {

        super.viewDidAppear(animated)

        scrollV.zoomScale = CGFloat(UserDefaults.standard.float(forKey: "currentZoom") )

        let x = CGFloat( UserDefaults.standard.float(forKey: "x"))

        let y = CGFloat( UserDefaults.standard.float(forKey: "y"))

        scrollV.contentOffset = CGPoint(x: x, y: y)

 

    }

    

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

        return imageV

    }

    

    private var currentZoom: CGFloat = 1

    func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {

        currentZoom = scale

        UserDefaults.standard.setValue(currentZoom, forKey: "currentZoom")

        print(scrollView.contentOffset)

        UserDefaults.standard.setValue(scrollView.contentOffset.x, forKey: "x")

        UserDefaults.standard.setValue(scrollView.contentOffset.y, forKey: "y")

    }

}

你可能感兴趣的:(iOS,开发,swift)