使 CollectionView 单元格中的某个视图可点击

问题描述 投票:0回答:1

我想使 collectionView 单元格中的某些视图可点击。

ViewController的代码

class ViewController: UIViewController {
    
    let collectionView:UICollectionView = {
        let view = UICollectionViewFlowLayout()
        view.scrollDirection = .horizontal
        let cv : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: view)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.showsHorizontalScrollIndicator = false
        cv.isPagingEnabled = true
        return cv
    }()
    
    let arrayData:[Data] = [Data(vectorImages: "Group 3", maskImages: "", rectangleImage: "", headingLabel: "Document Reader", detailText: "Lorem ipsum dolor sit amet consectetur. Sit tortor malesuada egestas velit magna. Egestas congue nisi tincidunt urna.",view: View(background: .systemPurple, cornerRadius: 12),labelInView: "Get Started"),
                            Data(vectorImages: "Group 10", maskImages: "Mask group-2", rectangleImage: "Rectangle 144", headingLabel:"Read and View", detailText: "Lorem ipsum dolor sit amet consectetur. Sit tortor malesuada egestas velit magna. Egestas congue nisi tincidunt urna.",view:View(background: .systemPurple, cornerRadius: 12),labelInView: "Get Started"),
                            Data(vectorImages: "Group 11", maskImages: "Mask group-3", rectangleImage: "Rectangle 144", headingLabel: "Read and View", detailText: "Lorem ipsum dolor sit amet consectetur. Sit tortor malesuada egestas velit magna. Egestas congue nisi tincidunt urna.",view: View(background: .systemPurple, cornerRadius: 12),labelInView: "Get Started"),
                            Data(vectorImages: "Group 12", maskImages: "Mask group-4", rectangleImage: "Rectangle 144", headingLabel: "Read and View", detailText: "Lorem ipsum dolor sit amet consectetur. Sit tortor malesuada egestas velit magna. Egestas congue nisi tincidunt urna.",view: View(background: .systemPurple, cornerRadius: 12),labelInView: "Get Started")]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemPurple
        
        setupView()
        setDelegatesAndDatasource()
        registerCell()
        
    }
    
    func setupView() {
        view.addSubview(collectionView)
        
        NSLayoutConstraint.activate([
            
            collectionView.topAnchor.constraint(equalTo: view.topAnchor),
            collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
            
        ])
    }
    
    func setDelegatesAndDatasource() {
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    
    func registerCell() {
        collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
    }
    
    
}

扩展视图控制器:

UICollectionViewDelegateFlowLayout,UICollectionViewDataSource {
 
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrayData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)as! CollectionViewCell
        cell.customView.vectorImage.image = UIImage(named: "\(arrayData[indexPath.row].vectorImages)")
        cell.customView.maskImage.image = UIImage(named: "\(arrayData[indexPath.row].maskImages)")
        cell.customView.rectangleView.image = UIImage(named:"\(arrayData[indexPath.row].rectangleImage)")
        cell.customView.heading.text = arrayData[indexPath.row].headingLabel
        cell.customView.detailText.text = arrayData[indexPath.row].detailText
        cell.customView.view = arrayData[indexPath.row].view as! View
        cell.customView.view.isUserInteractionEnabled = true
   cell.customView.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
        cell.customView.labelInView.text = arrayData[indexPath.row].labelInView
        
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 393 , height: 852)
    }
    @objc func handleTap() {
    let controller = SecondViewController()
    self.navigationController?.pushViewController(controller, animated: true)
}
}

在 CollectioView cell.customView.view 这个视图的这个单元格中,我希望它使其可点击

ScreenView的代码,在这个视图中我想使其可点击

import UIKit

class ScreenView: UIView {
    
    let rectangleView = ImageView(image: "")
    
    let maskImage = ImageView(image: "")
            
    let vectorImage = ImageView(image: "")
    
    let heading = Label(text: "Some Text", font: UIFont.systemFont(ofSize: 30, weight: .black), textColor: .black)
        
    
        let detailText:UILabel = {
            let lbl = UILabel()
            lbl.translatesAutoresizingMaskIntoConstraints = false
            lbl.font = .systemFont(ofSize: 14, weight: .light)
            lbl.numberOfLines = 0
            return lbl
        }()
    
    var view = View(background: .systemPurple, cornerRadius: 12)
    let labelInView = Label(text: "Get Started", font: UIFont.systemFont(ofSize: 14, weight: .black), textColor: .white)
    
    init(vectorImage:String, maskImage:String, rectangleView:String, labelHeading:String, labelText:String, view:UIView, viewLabel:String)
        {
            super.init(frame: .zero)
            self.translatesAutoresizingMaskIntoConstraints = false
            self.vectorImage.image = UIImage(named: vectorImage)
            self.maskImage.image = UIImage(named: maskImage)
            self.rectangleView.image = UIImage(named: rectangleView)
            heading.text = labelHeading
            detailText.text = labelText
            self.view = view as! View
            self.labelInView.text = viewLabel
            
            setupViews()
        }
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
     func setupViews() {
            
            addSubview(rectangleView)
            rectangleView.addSubview(maskImage)
            rectangleView.addSubview(vectorImage)
            addSubview(heading)
            addSubview(detailText)
            addSubview(view)
            view.addSubview(labelInView)
            
            NSLayoutConstraint.activate([
                
                rectangleView.centerYAnchor.constraint(equalTo: centerYAnchor),
                rectangleView.centerXAnchor.constraint(equalTo: centerXAnchor),
                rectangleView.widthAnchor.constraint(equalToConstant: 345),
                rectangleView.heightAnchor.constraint(equalToConstant: 441),
                
                maskImage.topAnchor.constraint(equalTo: rectangleView.topAnchor),
                maskImage.widthAnchor.constraint(equalToConstant: 345),
                
                vectorImage.bottomAnchor.constraint(equalTo: rectangleView.bottomAnchor, constant: -10),
                vectorImage.centerXAnchor.constraint(equalTo: rectangleView.centerXAnchor),
                vectorImage.widthAnchor.constraint(equalToConstant: 313),
                vectorImage.heightAnchor.constraint(equalToConstant: 251),
                
                heading.topAnchor.constraint(equalTo: rectangleView.bottomAnchor, constant: 20),
                heading.centerXAnchor.constraint(equalTo: centerXAnchor),
                
                detailText.topAnchor.constraint(equalTo: heading.bottomAnchor, constant: 20),
                detailText.centerXAnchor.constraint(equalTo: centerXAnchor),
                detailText.widthAnchor.constraint(equalToConstant: 313),
                
                view.topAnchor.constraint(equalTo: detailText.bottomAnchor, constant: 74),
                view.leadingAnchor.constraint(equalTo: rectangleView.leadingAnchor ),
                view.widthAnchor.constraint(equalToConstant: 345),
                view.heightAnchor.constraint(equalToConstant: 52),
                
                labelInView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
                labelInView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
            ])
        }
}

CollectionView中CustomCell的代码 导入 UIKit

class CollectionViewCell: UICollectionViewCell {
    
    
    let customView = ScreenView(vectorImage: "", maskImage: "", rectangleView: "", labelHeading: "Some Text", labelText: "Text you", view:View(background: .systemPurple, cornerRadius: 12), viewLabel: "Get Started")
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupView() {
        
            addSubview(customView)
        
        NSLayoutConstraint.activate([
            customView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -100),
            customView.centerXAnchor.constraint(equalTo: centerXAnchor)
            
        ])
    }
    
}
ios swift uicollectionview uicollectionviewcell collectionview
1个回答
0
投票

首先,给未来一些建议......

在此处发布问题时,请确保您的代码将按原样运行。如果我们可以复制/粘贴/运行而不必猜测缺少的代码可能是什么,那么提供帮助就会容易得多。

另外,从简单开始!!!从实现目标所需的最少代码开始。

在这种情况下,让我们使用带有单个子视图的单元格类。


View Controller 类 - 非常标准。我们将使用一组颜色,用于设置每个单元格中“自定义视图”的背景。

class ViewController: UIViewController {

    let collectionView:UICollectionView = {
        let view = UICollectionViewFlowLayout()
        view.scrollDirection = .horizontal
        let cv : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: view)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.showsHorizontalScrollIndicator = false
        cv.isPagingEnabled = true
        return cv
    }()
    
    let arrayData: [UIColor] = [
        .systemRed, .systemGreen, .systemBlue, .systemYellow,
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupView()
        setDelegatesAndDatasource()
        registerCell()
    }
    
    func setupView() {
        view.addSubview(collectionView)
        
        NSLayoutConstraint.activate([
            
            collectionView.topAnchor.constraint(equalTo: view.topAnchor),
            collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
            
        ])
    }
    
    func setDelegatesAndDatasource() {
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    
    func registerCell() {
        collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
    }
}

视图控制器扩展

extension ViewController: UICollectionViewDelegateFlowLayout,UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrayData.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)as! CollectionViewCell
        cell.customView.backgroundColor = arrayData[indexPath.item]
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 393 , height: 852)
    }
}

自定义单元格类 - 将单个

UIView
作为子视图,我们将向其中添加
UITapGestureRecognizer
。点击时,我们将打印到调试控制台,并且我们还将“闪烁”背景颜色,以便我们看到它对点击做出了响应。

class CollectionViewCell: UICollectionViewCell {

    let customView = UIView()
    
    @objc func handleTap(_ t: UITapGestureRecognizer) {
        
        print("Got Tap!")
        
        // let's "flash" the customView's background color
        //  so we have a visual indication it was tapped
        let c = customView.backgroundColor
        customView.backgroundColor = .yellow
        UIView.animate(withDuration: 0.75, animations: {
            self.customView.backgroundColor = c
        })
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
        
        // create and add Tap Gesture Recognizer to customView
        let t = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        customView.addGestureRecognizer(t)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupView() {
        
        customView.layer.cornerRadius = 12
        customView.translatesAutoresizingMaskIntoConstraints = false
        
        // make sure we addSubview to contentView !!
        contentView.addSubview(customView)
        
        NSLayoutConstraint.activate([
            customView.widthAnchor.constraint(equalToConstant: 300.0),
            customView.heightAnchor.constraint(equalToConstant: 400.0),
            customView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -100),
            customView.centerXAnchor.constraint(equalTo: centerXAnchor),
        ])
    }
    
}
© www.soinside.com 2019 - 2024. All rights reserved.