我的目标是创建像苹果照片应用程序的应用程序 - 显示照片,允许缩放,水平滚动等...
我目前无法在collectionViewCell
中缩放照片。
我做了什么:collectionView
scrollView
collectionViewCell
内UIImageView
。这就是我在CollectionViewController
中的cellForItemAtIndexPath
内创建 let imageView: UIImageView!
let someImage = UIImage(named: "someImage")
imageView = UIImageView(image: someImage)
imageView.frame = CGRect(origin: CGPointMake(0.0, 0.0), size:someImage.size)
cell.scrollView.addSubview(imageView)
cell.scrollView.contentSize = someImage.size
let scrollViewFrame = cell.scrollView.frame
let scaleWidth = scrollViewFrame.size.width / cell.scrollView.contentSize.width
let scaleHeight = scrollViewFrame.size.height / cell.scrollView.contentSize.height
let minScale = min(scaleWidth, scaleHeight);
cell.scrollView.minimumZoomScale = minScale;
cell.scrollView.maximumZoomScale = 1.0
cell.scrollView.zoomScale = minScale;
centerScrollViewContents(cell.scrollView, imageView: imageView)
的方式:
func viewForZoomingInScrollView(scrollView: UIScrollView!) -> UIView! {
return imageView
}
func scrollViewDidZoom(scrollView: UIScrollView!) {
let boundsSize = scrollView.bounds.size
var contentsFrame = imageView.frame
if contentsFrame.size.width < boundsSize.width {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0
} else {
contentsFrame.origin.x = 0.0
}
if contentsFrame.size.height < boundsSize.height {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0
} else {
contentsFrame.origin.y = 0.0
}
imageView.frame = contentsFrame
}
(我在Ray Wenderlich上找到了这段代码)
接下来我需要添加此代码,以便缩放可以正常工作:
IBAOutlet
问题是,我scrollView
的{{1}}位于CollectionViewCell
内,而不是CollectionViewController
,所以这两个函数必须从CollectionViewCell
调用,但是我不知道如何访问imageView
viewForZoomingInScrollView
。也许我的整个方法都错了?
答案 0 :(得分:1)
使用xib
创建UICollectionViewCell 子类Subclassing UICollectionViewCell and initialising from xib
或没有xib
http://randexdev.com/2014/08/uicollectionviewcell/
然后为 scrollView 设置委托是 collectionViewCell 子类
将UIScrollViewDelegate代码添加到单元格
您可以从单元格属性
访问imageView