khuong291 khuong291 - 7 months ago 44
Swift Question

Remove the subView inside Cell

In my

ViewController
, I have a variable:

var shareButtonTapped = false


I want when I click the
shareButton
on the
navigationBar
, it will show the shareButton all of the cell, except the cell which indexPath.row == 0.

Here is the action of
shareButton
:

@IBAction func shareButtonTapped(sender: AnyObject) {
shareButtonTapped = !shareButtonTapped
collectionView.reloadData()
}


And here is the CollectionViewDataSource method:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! GiftCollectionViewCell

if shareButtonTapped {

cell.gift = gifts[indexPath.row]
let shareButton = FBSDKShareButton(frame: CGRect(x: 0, y: 0, width: 80, height: 30))
shareButton.tag = 1
let photo = FBSDKSharePhoto()
photo.image = gifts[indexPath.row].image
photo.userGenerated = true
let content = FBSDKSharePhotoContent()
content.photos = [photo]
content.contentURL = NSURL(string: "http://www.fantageek.com")
shareButton.shareContent = content

cell.contentView.addSubview(shareButton)
return cell
} else {
cell.gift = gifts[indexPath.row]
return cell
}

}


It worked:

enter image description here

But I want to click this
shareButton
on
NavigationBar
again, all of
shareButton
inside each cell will disappear. How to do this?

Any helps would be appreciated. Thanks.

Answer

Use removeFromSuperview() method inside your else block:

else {
    cell.gift = gifts[indexPath.row]
    for subview in cell.contentView.subviews {
        if subview is FBSDKShareButton {
            subview.removeFromSuperview()
        }
    }
    return cell
}