在UIScrollView上实现缩放

时间:2019-04-24 18:46:54

标签: ios swift xcode uiscrollview uiimageview

我已经插入了delagates和正确的代码,以便缩放功能可以在UIScrollView上工作。但是,当我运行代码时,最小或最大缩放值返回“零”。我不明白如何绕过这个。有什么建议吗?

import UIKit
import MapKit
import MessageUI

class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet var scrollView: UIScrollView!
    @IBOutlet var tylenol: UIImageView!

    let backgroundImageView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()
        setBackground()

        self.scrollView.minimumZoomScale = 1.0
        self.scrollView.maximumZoomScale = 6.0
    }

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


    func setBackground() {
        view.addSubview(backgroundImageView)
        backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
        backgroundImageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        backgroundImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        backgroundImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        backgroundImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

        backgroundImageView.image = UIImage(named: "background")
        view.sendSubviewToBack(backgroundImageView)
    }

2 个答案:

答案 0 :(得分:1)

崩溃是由于尝试打开宣告为非可选的一个或两个插座引起的。这些未在情节提要中正确连接。

@IBOutlet var scrollView: UIScrollView!
@IBOutlet var tylenol: UIImageView!

尽管与您的问题无关,但应将它们声明为以下形式,以避免保留周期:

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var tylenol: UIImageView!

在情节提要中,确保已设置所有这些内容:

Check your view controller is of the correct class check scrollview connections check Tylenol connection

答案 1 :(得分:0)

您应将minimumZoomScalemaximumZoomScale的值设置为大于1.0