create a custom uicollectionview cell with an uiimageview and a uibutton in swift

To create a custom UICollectionView cell with an UIImageView and a UIButton in Swift, follow these steps:

  1. Create a new subclass of UICollectionViewCell and name it CustomCollectionViewCell.
main.swift
class CustomCollectionViewCell: UICollectionViewCell {
    
}
62 chars
4 lines
  1. Add an UIImageView and a UIButton as subviews of the cell in the init method.
main.swift
class CustomCollectionViewCell: UICollectionViewCell {
    let imageView = UIImageView()
    let button = UIButton()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // Add subviews
        contentView.addSubview(imageView)
        contentView.addSubview(button)
        
        // Configure image view
        imageView.contentMode = .scaleAspectFit
        
        // Configure button
        button.setTitle("Button", for: .normal)
        button.setTitleColor(.black, for: .normal)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
654 chars
24 lines
  1. Override the layoutSubviews method to layout the subviews.
main.swift
class CustomCollectionViewCell: UICollectionViewCell {
    let imageView = UIImageView()
    let button = UIButton()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // Add subviews
        contentView.addSubview(imageView)
        contentView.addSubview(button)
        
        // Configure image view
        imageView.contentMode = .scaleAspectFit
        
        // Configure button
        button.setTitle("Button", for: .normal)
        button.setTitleColor(.black, for: .normal)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // Layout subviews
        imageView.frame = contentView.bounds
        button.frame = CGRect(x: 0, y: contentView.frame.height - 30, width: contentView.frame.width, height: 30)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
928 chars
32 lines
  1. Use the custom cell in your UICollectionView by registering it with the class.
main.swift
collectionView.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "CustomCell")
97 chars
2 lines
  1. Dequeue the custom cell in your UICollectionViewDataSource's collectionView(_:cellForItemAt:) method and configure it.
main.swift
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCollectionViewCell
    
    // Configure cell
    cell.imageView.image = UIImage(named: "image.png")
    cell.button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    
    return cell
}
439 chars
10 lines

gistlibby LogSnag