编辑:我已更新了问题代码,以便现在可以帮助任何人。
我在scrollView
中有一个UICollectionViewCell
,但无法通过捏合在模拟器中使用缩放功能。我可以通过手动缩放视图来实现这一点,但是当用户捏缩放时我需要将图像视图框更改为完整尺寸。现在它的大小填充框架宽度设置为屏幕宽度和框架高度设置为屏幕高度。我需要动态地将帧宽更改为等于帧高,因为图像是方形的。
这是我的代码:
import UIKit
class MyCollectionViewCell: UICollectionViewCell, UIScrollViewDelegate {
let screenWidth = UIScreen.main.bounds.width
let activityIndicator: UIActivityIndicatorView = {
let spinner = UIActivityIndicatorView()
spinner.activityIndicatorViewStyle = .white
spinner.color = Constants.APP_SPINNER_COLOR
spinner.hidesWhenStopped = true
return spinner
}()
var zoomScrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.backgroundColor = .white
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 6.0
scrollView.clipsToBounds = true
scrollView.isUserInteractionEnabled = true
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
var itemImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = .white
imageView.isUserInteractionEnabled = true
return imageView
}()
func viewForZooming(in zoomScrollView: UIScrollView) -> UIView? {
return itemImageView
}
override init(frame: CGRect) {
super.init(frame: frame)
zoomScrollView.delegate = self
contentView.backgroundColor = .white
contentView.addSubview(zoomScrollView)
zoomScrollView.addSubview(itemImageView)
itemImageView.addSubview(activityIndicator)
zoomImageView.frame = CGRect(x:0, y:0, width: screenWidth, height: screenHeight)
zoomScrollView.frame = itemImageView.frame
activityIndicator.anchorCenterXToSuperview()
activityIndicator.anchorCenterYToSuperview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
答案 0 :(得分:1)
您需要设置捏缩放的scrollView.contentSize
才能生效。见https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/UIScrollView_pg/CreatingBasicScrollViews/CreatingBasicScrollViews.html
答案 1 :(得分:1)
这里制作Scroll View的简单演示。
注意:不对图像视图赋予任何约束
下面的scrollview代码:
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
var imgDemo: UIImageView = {
let img = UIImageView()
img.contentMode = .scaleAspectFill
img.isUserInteractionEnabled = true
return img
}()
var scrollView:UIScrollView = {
let scroll = UIScrollView()
scroll.maximumZoomScale = 4.0
scroll.minimumZoomScale = 0.25
scroll.clipsToBounds = true
return scroll
}()
override func viewDidLoad() {
super.viewDidLoad()
imgDemo.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
imgDemo.image = UIImage(named: "5.jpg")
scrollView.delegate = self
scrollView.frame = imgDemo.frame
scrollView.addSubview(imgDemo)
view.addSubview(scrollView)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imgDemo
}
}