swiftmaterial-designmd-chip

MDCChip selected image is displacing my title label


I'm implementing MDCChips in collection views in my application, but I'm encountering an issue that I can't solve.

When I add an selectedImageView to my chip and I select the chip in my collection view, the image is shown as intended, but the title is displaced due to the apparition of the image.

I've tried playing with the intrinsic content and the UIEdgeInsets, but I can't seem to find a workaround for this.

Is there some way to avoid this happening? I'd like the image to appear without displacing anything else in the chip view.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifierChips", for: indexPath) as! MDCChipCollectionViewCell
    let chipView = cell.chipView
    chipView.selectedImageView.image = UIImage(named: "tickIcon")

    return cell
}

Any tip or help will be appreciated!


Solution

  • I finally managed to achieve it. It is kinda hacky, but as long as it works... And lacking another solution... Suits me!

    I added this code to be executed every time the cell is selected.

    chipView.imagePadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -padding)
    

    And this code to be executed every time the cell is deselected.

    chipView.imagePadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    

    So esentially the padding value is the width of the image, when you select the cell the image will appear but you remove the right padding of the image with the total width of the image, so it doesn't affect the label.

    When you deselect the view, the image will disappear so you restore the padding to zero.