2017-08-03 65 views
0

我必須走這uicollectionviewcellUICollectionViewcell調用函數遍地

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
{ 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell 
    if let CurrentPost = posts[indexPath.row] as? Post{ 
     //determine which constraint to call 
     if(CurrentPost.PostText != nil){ 
      if(CurrentPost.PostImage != nil){ 
       cell.postImage.image = CurrentPost.PostImage 
       cell.cellConstraintsWithImageWithText() 
      }else{ 
       cell.postImage.image = nil 
       cell.cellConstraintsWithoutImageWithText() 
      } 
     }else{ 
      cell.postImage.image = CurrentPost.PostImage 
      cell.cellConstraintsWithImageWithoutText() 
     } 
    } 
    return cell 
} 

我的目標是確定基於缺乏或圖像和text.Now的存在其功能是目標的問題是所有這些功能被調用,因爲一些細胞確實有圖像cellConstraintsWithImageWithText正在被調用,其他人沒有它們,所以cellConstraintsWithoutImageWithText正在被調用。我怎樣才能爲單個細胞而不是所有細胞調用單個函數?

回答

0

發生這種情況是因爲單元格正在被重用。處理這個問題最簡單的方法就是在視圖控制器中存儲帶有文本的單元格的索引路徑。當單元格出隊時,只需檢查索引路徑是否存在於存儲陣列和佈局中。

在你ViewController

var cellsWithText: [IndexPath] = [] 

cellForItemAt indexPath

... 
cell.postImage.image = nil 
cell.cellConstraintsWithoutImageWithText() 
if !cellsWithText.contains(indexPath) { 
    cellsWithText.append(indexPath) 
} 
... 

現在在開始在cellForItemAt indexPath

if let CurrentPost = posts[indexPath.row] as? Post { 
    if cellsWithText.contains(indexPath) { 
    // layout for text 
    } else { 
    // layout for image 
    } 

我也注意到,傻冒使用posts[indexPath.row]但您使用COLLEC tionView,它沒有行並且具有item。這也可能是問題。

+0

這不正是我在做什麼? – sakoaskoaso

+0

@sakoaskoasko你正在存儲帖子,我提供存儲索引路徑。在初始出列時,只需將單元格的索引路徑添加到數組中(如果它具有文本)。當集合視圖將再次取消該單元格時,它應檢查此單元格的索引路徑是否存在於數組中。如果是這樣,這是一個文字佈局,如果不是圖像。 – inokey

+0

@sakoaskoaso嘿,我用一些代碼更新了答案,並且還注意到我對indexPath.row的評論 – inokey