2016-04-23 106 views
1

子視圖在我ViewController,我有一個變量:取出內細胞

var shareButtonTapped = false 

我想,當我點擊shareButtonnavigationBar,它會顯示shareButton所有的細胞,除了電池,其indexPath .row == 0,

這裏是shareButton動作:

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

這裏是CollectionViewDataSource方法:

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 
     } 

    } 

它的工作:

enter image description here

但我想再次點擊此shareButtonNavigationBar,所有的shareButton內的每個細胞就會消失。這個怎麼做?

任何幫助,將不勝感激。謝謝。

回答

1

使用removeFromSuperview()方法您else塊內:

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

感謝您幫助。 – Khuong

1

更好的方法是保持共享按鈕永遠是細胞的組成部分。並基於bar按鈕的shareButtonTapped狀態顯示並隱藏該按鈕。

比方說,你的按鈕名稱爲shareImage然後cellForRow

cell.shareButton.hidden = false 
if(shareButtonTapped){ 
    cell.shareButton.hidden = true 
} 
+0

感謝您的幫助。 – Khuong

+0

刪除和添加子視圖不是一種好方法,除非這是唯一的選擇。 –

+0

不錯。我試過了。這更好,因爲我同時保存和分享按鈕。 – Khuong