2017-04-25 28 views
1

好日子,我只在Objective-C或Swift 2中看到过这个例子,但还没有在Swift 3中运行过Xcode 8.我的情况是我有一个带有一套图像,我希望它们在用户点击它们时被放大。这里是我的代码:Swift 3:在CollectionView中选择时放大图像

@IBOutlet weak var collectionView: UICollectionView! 


var images = ["catPic1.jpg", "catPic2.jpg", "catPic3.jpg"] 

override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 

     collectionView.delegate = self 

     collectionView.dataSource = self 

    } // end of view did load 

public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    { 
     return images.count 
    } 

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
    { 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell" , for: indexPath) as! CustomCell 

     cell.myImage.image = UIImage(named: images[indexPath.row]) 


     return cell 

    } 

顺便说一句,我在另一个迅速类集合视图单元代码。下面的代码:

class CustomCell: UICollectionViewCell { 

    @IBOutlet weak var myImage: UIImageView! 
} 

所有的图像都显示正常,我只需要在用户选择他们他们以某种方式放大。谢谢。

回答

1

您可以使用另一种UIImageView来全屏查看图像

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

    let imageView = UIImageView(image: UIImage(named: images[indexPath.row])) 
    imageView.frame = self.view.frame 
    imageView.backgroundColor = .black 
    imageView.contentMode = .top 
    imageView.isUserInteractionEnabled = true 

    let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage)) 
    imageView.addGestureRecognizer(tap) 

    self.view.addSubview(imageView) 
} 

// Use to back from full mode 
func dismissFullscreenImage(_ sender: UITapGestureRecognizer) { 
    sender.view?.removeFromSuperview() 
} 
+0

谢谢!这工作。唯一的一点是它不会将图像放在缩放视图中(当它将其全屏显示时)。某些图像显得过于接近或未完全显示。 @Luan Tran – Angel

+0

嗨。我很乐意帮助你。您可以更改'contentMode'作为图片的中心。更改为'imageView.contentMode = .center'或'imageView.contentMode = .scaleAspectFit' –

+0

完美!非常感谢。 @Luan Tran – Angel