无法在 swift 中使用滚动视图滚动图像
Posted
技术标签:
【中文标题】无法在 swift 中使用滚动视图滚动图像【英文标题】:Unable to scroll image using scroll view in swift 【发布时间】:2017-06-06 16:54:24 【问题描述】:我在快速滚动视图中遇到了这个奇怪的问题,即使在文件中定义滚动视图后图像也不会滚动,我还添加了缩放并且效果很好。请在这件事上给予我帮助 https://pastebin.com/1uC3fqHG
import UIKit
class ImageViewController: UIViewController
var imageURL: URL?
didSet
image = nil
if view.window != nil
fetchImage()
private func fetchImage()
if let url = imageURL
let urlContents = try? Data(contentsOf: url)
if let imageData = urlContents
image = UIImage(data: imageData)
override func viewDidLoad()
super.viewDidLoad()
view.addSubview(imageView)
imageURL = URL(string: "http://www.lamborghini.com/en-en/sites/en-en/files/DAM/lamborghini/share%20img/huracan-coupe-facebook-og.jpg")
override func viewWillAppear(_ animated: Bool)
super.viewWillAppear(animated)
if image == nil
fetchImage()
@IBOutlet weak var scrollView: UIScrollView!
didSet
scrollView.delegate = self
scrollView.minimumZoomScale = 0.03
scrollView.maximumZoomScale = 2.0
scrollView.contentSize = imageView.frame.size
scrollView.addSubview(imageView)
fileprivate var imageView = UIImageView()
private var image: UIImage?
get
return imageView.image
set
imageView.image = newValue
imageView.sizeToFit()
scrollView?.contentSize = imageView.frame.size
extension ImageViewController: UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView?
return imageView
【问题讨论】:
【参考方案1】:问题是您在 viewDidLoad() 中将图像添加到视图中。从 viewDidLoad() 中删除 view.addSubview(imageView)
,一切都会正常工作。
代码会变成如下
import UIKit
class ImageViewController: UIViewController
var imageURL: URL?
didSet
image = nil
if view.window != nil
fetchImage()
private func fetchImage()
if let url = imageURL
let urlContents = try? Data(contentsOf: url)
if let imageData = urlContents
image = UIImage(data: imageData)
override func viewDidLoad()
super.viewDidLoad()
imageURL = URL(string: "http://www.lamborghini.com/en-en/sites/en-en/files/DAM/lamborghini/share%20img/huracan-coupe-facebook-og.jpg")
override func viewWillAppear(_ animated: Bool)
super.viewWillAppear(animated)
if image == nil
fetchImage()
@IBOutlet weak var scrollView: UIScrollView!
didSet
scrollView.delegate = self
scrollView.minimumZoomScale = 0.03
scrollView.maximumZoomScale = 2.0
scrollView.contentSize = imageView.frame.size
scrollView.addSubview(imageView)
fileprivate var imageView = UIImageView()
private var image: UIImage?
get
return imageView.image
set
imageView.image = newValue
imageView.sizeToFit()
scrollView?.contentSize = imageView.frame.size
extension ImageViewController: UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView?
return imageView
【讨论】:
【参考方案2】:您应该更新内容大小并更新图像视图约束检查此tutorial
【讨论】:
以上是关于无法在 swift 中使用滚动视图滚动图像的主要内容,如果未能解决你的问题,请参考以下文章