Search code examples
uibuttonframeuicollectionviewcellcgrectbounds

Swift iOS- How to Add Button to the outside a CollectionView Cell


  1. I want to get a deleteButton that is a delete image to sit on the outside of a collectionViewCell (it can be partially inside).

enter image description here

  1. I looked at other SO answers and they said just play with the button's frame's Rect's x & y values which I did. When I set the x & y values to 0,0 I get:

     class CustomCell: UICollectionViewCell {
    
     @IBOutlet weak var imageView: UIImageView!
     var deleteButton: UIButton!
     var deleteButtonImg: UIImage!
    
     override func awakeFromNib() {
         super.awakeFromNib()
    
     deleteButton = UIButton(frame: CGRect(x: 0, y: 0, width: frame.size.width/4, height: frame.size.width/4))
    
     deleteButtonImg = UIImage(named: "delete-icon")!.withRenderingMode(.alwaysTemplate)
     deleteButton.setImage(deleteButtonImg, for: .normal)
     deleteButton.tintColor = UIColor.red
    
     contentView.addSubview(deleteButton)
     }
    

enter image description here

  1. When I try to set the the Rect's x & y to -10,-10 the deleteButton gets clipped inside the cell's imageView. I don't have clipsToBounds set.

     deleteButton = UIButton(frame: CGRect(x: -10, y: -10, width: frame.size.width/4, height: frame.size.width/4))
    

enter image description here

I even tried setting clipToBounds to false but I get the same effect as pic # 3.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell

        cell.imageView.image = myImageArray[indexPath.row]
        cell.imageView.clipsToBounds = false

        return cell
    }

Where am I going wrong?


Solution

  • The problem was inside storyboard I had a:

    CollectionView
          -CustomCell (type collectionViewCell)
               -imageView
    

    Under the Attributes Inspector, in the Drawing section, all 3 of these have the property clipsToBounds.

    I overlooked the fact that I had clipsToBounds set to false (unchecked) on the imageView but set to true (checked) on the CustomCell and the CollectionView.

    enter image description here

    enter image description here

    enter image description here

    enter image description here

    If anyone else has this problem make sure you uncheck clipsToBounds on the collectionView, collectionViewCell, and the imageView.