我被困在这几个小时。我想要的只是ScrollView中的ImageView。我希望将contentMode设置为aspect fill,这样图像每次都会填充ImageView。我还希望用户能够缩放和平移图像。这是我的代码:
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
var scrollView: UIScrollView!
var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let image = UIImage(named: "fish")!
imageView = UIImageView(image: image)
imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size:image.size)
imageView.contentMode = .scaleAspectFill
scrollView = UIScrollView(frame: view.bounds)
scrollView.backgroundColor = UIColor.black
scrollView.contentSize = imageView.bounds.size
scrollView.delegate = self
scrollView.minimumZoomScale = 0.1
scrollView.maximumZoomScale = 4.0
scrollView.zoomScale = 1.0
scrollView.addSubview(imageView)
view.addSubview(scrollView)
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
}
首先我无法放大或缩小,不明白为什么。我设置了委托,实现了 viewForZoomingInScrollView ,并根据缩放工作所需的内容设置了 maximumZoomScale 。
其次,图像不适合屏幕。内容模式设置似乎不会影响任何内容,因为当我将其设置为.scaleToFill时,图像不会挤进屏幕,我可以平移它。
小于屏幕的图像: http://i.imgur.com/eEuy0En.png
原件: http://i.imgur.com/GtkKWKu.jpg
图片大于屏幕: http://i.imgur.com/1cH4rrk.png
原件: http://i.imgur.com/ThNhapb.jpg
较小的图像应该填充屏幕,但它不会,并且缩放在两种情况下都不起作用。我只能在较大的图像周围平移。
答案 0 :(得分:1)
请试试这个:
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView!
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
self.scrollView.flashScrollIndicators()
}
答案 1 :(得分:1)
您的问题是UIScrollViewDelegate
方法
应
func viewForZooming(in scrollView: UIScrollView) -> UIView?
希望这有助于你
答案 2 :(得分:0)
创建两个出口:---
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imgPhoto: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 6.0
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imgPhoto
}
其他代码
let image = UIImage(named: "fish")!
imageView = UIImageView(image: image)
imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size:image.size)
// imageView.contentMode = .scaleAspectFill
//
scrollView = UIScrollView(frame: view.bounds)
// scrollView.backgroundColor = UIColor.black
// scrollView.contentSize = imageView.bounds.size
scrollView.delegate = self
scrollView.minimumZoomScale = 0.1
scrollView.maximumZoomScale = 4.0
//scrollView.zoomScale = 1.0
scrollView.addSubview(imageView)
view.addSubview(scrollView)