Reputation: 59
Good day, I have only seen examples of this in Objective-C or Swift 2 but not yet in Swift 3 running Xcode 8. My situation is that I have a collection view with a set of images and I want them to be enlarged when the user taps on them. Here is my code:
@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
}
By the way, I have the collection view cell code in another swift class. Here's the code:
class CustomCell: UICollectionViewCell {
@IBOutlet weak var myImage: UIImageView!
}
All the images are showing correctly, I just need them to somehow enlarge when the user selects them. Thanks.
Upvotes: 2
Views: 4267
Reputation: 1142
You can use another UIImageView
to view fullscreen your image
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()
}
Upvotes: 7