问题描述
我对此很陌生,而且我没有太多知识。我按照教程并以编程方式创建了 UICollectionView 。现在我想用从 UICollectionViewCell 中选择的图像打开一个新视图。我附上了我写的整个代码。还有什么方法可以根据屏幕尺寸设置单元格大小(我希望每个屏幕尺寸的单元格大约为 300 x 300)。非常感谢任何帮助。
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"),customData(title: "City Sunset",image: #imageLiteral(resourceName: "Image7"),customData(title: "Toronto 1",image: #imageLiteral(resourceName: "Image5"),customData(title: "Beach Sunset",image: #imageLiteral(resourceName: "Image15"),customData(title: "Mounatin Sunset",image: #imageLiteral(resourceName: "Image13"),customData(title: "Girl",image: #imageLiteral(resourceName: "Image8"),customData(title: "Butterfly",image: #imageLiteral(resourceName: "Image6"),customData(title: "Deers",image: #imageLiteral(resourceName: "Image17"),customData(title: "Beach",image: #imageLiteral(resourceName: "Image16"),customData(title: "Mackaw",image: #imageLiteral(resourceName: "Image11"),customData(title: "Penguin",image: #imageLiteral(resourceName: "Image1"),customData(title: "Los Angeles",image: #imageLiteral(resourceName: "Image2"),customData(title: "Cat",image: #imageLiteral(resourceName: "Image9"),customData(title: "Big Sur",image: #imageLiteral(resourceName: "Image12"),customData(title: "Night City",image: #imageLiteral(resourceName: "Image14"),]
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,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")
}
}
解决方法
您可以简单地使用 UICollectionView 委托方法 didSelectItemAt
,如下所示:
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
}
func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
// your code after click \(indexPath.item) cell
}
}