Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

ios - Open new view after tapping image in UICollectionView

I am fairly new to this and I do not have much knowledge. I followed a tutorial and created the UICollectionView programmatically. Now I want to open a new view with the image that was selected from the UICollectionViewCell. I have attached the entire code I wrote. Also is there any way to set up the cell size based on the screen size (I want the cell to be around 300 x 300 on each screen size). Any help is greatly appreciated.

import UIKit

struct customData {
    var title: String
    var image:UIImage
    var url:String
}

class ViewController: UIViewController {
    
   let data =
    [
        customData(title: "Lion", image: #imageLiteral(resourceName: "Image10"), url: "Hi"),
        customData(title: "Sea Sunset", image: #imageLiteral(resourceName: "Image4"), url: "Hi"),
        customData(title: "City Sunset", image: #imageLiteral(resourceName: "Image7"), url: "Hi"),
        customData(title: "Toronto 1", image: #imageLiteral(resourceName: "Image5"), url: "Hi"),
        customData(title: "Beach Sunset", image: #imageLiteral(resourceName: "Image15"), url: "Hi"),
        customData(title: "Mounatin Sunset", image: #imageLiteral(resourceName: "Image13"), url: "Hi"),
        customData(title: "Girl", image: #imageLiteral(resourceName: "Image8"), url: "Hi"),
        customData(title: "Butterfly", image: #imageLiteral(resourceName: "Image6"), url: "Hi"),
        customData(title: "Deers", image: #imageLiteral(resourceName: "Image17"), url: "Hi"),
        customData(title: "Beach", image: #imageLiteral(resourceName: "Image16"), url: "Hi"),
        customData(title: "Mackaw", image: #imageLiteral(resourceName: "Image11"), url: "Hi"),
        customData(title: "Penguin", image: #imageLiteral(resourceName: "Image1"), url: "Hi"),
        customData(title: "Los Angeles", image: #imageLiteral(resourceName: "Image2"), url: "Hi"),
        customData(title: "Cat", image: #imageLiteral(resourceName: "Image9"), url: "Hi"),
        customData(title: "Big Sur", image: #imageLiteral(resourceName: "Image12"), url: "Hi"),
        customData(title: "Night City", image: #imageLiteral(resourceName: "Image14"), url: "Hi"),
    ]

    
    
    fileprivate let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.register(CustomCell.self, forCellWithReuseIdentifier: "MyCell")
        return cv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        view.addSubview(collectionView)
        collectionView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 225).isActive = true
        collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
        collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -5).isActive = true
        collectionView.heightAnchor.constraint(equalTo: collectionView.widthAnchor, multiplier: 0.9).isActive = true
        
        collectionView.delegate = self
        collectionView.dataSource = self
        
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let secondVC = segue.destination as! SecondViewController
        secondVC.imageToDisplay = UserDefaults.standard.string(forKey: "TheImage") ?? "Image1"
    }
}

extension ViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 300 , height: 300 )
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CustomCell
        cell.data = self.data[indexPath.row]
        return cell
    }
    
    
}

class CustomCell: UICollectionViewCell
{
    
    var nameLabel:  UILabel!
    
    var data: customData?{
        didSet{
            guard let data = data else { return  }
            //bg.image = data.image
            bg.image = data.image
        }
    }
    
    let bg: UIImageView = {
        
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        iv.layer.cornerRadius = 25
        iv.layer.borderWidth = 3
        iv.layer.borderColor = UIColor(white: 1, alpha: 0.5).cgColor
        
        //tap gesture
        iv.isUserInteractionEnabled = true
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
        iv.addGestureRecognizer(tapGestureRecognizer)
        
        return iv
    }()
    
    @objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
   {
        print("(data?.title ?? "Unknown") was tapped")
   }
    
    
    override init(frame:CGRect)
    {
        super.init(frame: frame)
        
        contentView.addSubview(bg)
        bg.topAnchor.constraint(equalTo: topAnchor).isActive = true
        bg.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        bg.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        bg.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        
        bg.isUserInteractionEnabled = true
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
        bg.addGestureRecognizer(tapGestureRecognizer)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use UICollectionViewDelegateFlowLayout protocol to adjust the dimensions of each Cell Size, Like the code below:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return .init(width: 300.0, height: 300.0)
    }

Here you can adjust any dimensions you want. See the link below for more information:? UICollectionViewDelegateFlowLayout


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...