2016-05-03 54 views
1

在我的應用程序,我寫了下面的代碼在UICollectionViewcellForRowAtIndexpath這樣[CollectionView Cell is a custom cell]iOS單元格添加目標無法正常工作?

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 

    CollectionViewCell *cell = (CollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"localMusicCell" forIndexPath:indexPath]; 

[[cell.downImageButton viewWithTag:indexPath.item] addTarget:self action:@selector(downImgClicked:) forControlEvents:UIControlEventTouchUpInside]; 

return cell; 
} 

和目標的方法是這樣的:

-(void)downImgClicked:(UIButton*)button{ 

} 

而且還有在UICollectionView四個項目,但對於第一個項目只有這個目標方法被調用,其餘的他們甚至不觸發爲什麼?

+2

我想你想'[cell.downImageButton addTarget:自我行動:@選擇(downImgClicked :) forControlEvents:UIControlEventTouchUpInside] ;' – Nishant

+0

@Nishant我需要通過indexPath.item也是目標嗎?怎麼樣? – Group

+1

使用'cell.downImageButton.tag = indexPath.item;'然後在目標方法中,' - (void)downImgClicked:(UIButton *)按鈕int indexPathItem = button.tag; }' – Nishant

回答

3

嘗試另一種方法

cell.downImageButton.tag = indexPath.item; 
[cell.downImageButton addTarget:self action:@selector(downImgClicked:) forControlEvents:UIControlEventTouchUpInside]; 

呼叫的方法等

-(void)downImgClicked:(UIButton*)button{ 
    NSLog (@"selected index ==%@",button.tag); 
} 
+1

我的代碼有什麼問題? – Group

+0

兄弟沒什麼問題,有時userinteaction不可接收可能是 –

2
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 

    CollectionViewCell *cell = (CollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"localMusicCell" forIndexPath:indexPath]; 

    cell.downImageButton.tag =indexPath.row; 
    [cell.downImageButton addTarget:self action:@selector(downImgClicked:) forControlEvents:UIControlEventTouchUpInside]; 

    return cell; 

} 

和類似這樣的目標方法:

-(void)downImgClicked:(UIButton*)button 
{ 
long selectedBtnRow; 

selectedBtnRow = button.tag; 

NSLog (@"selected index ==>%ld",selectedBtnRow); 
} 
3

嘗試這種方式,

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


     let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! AllCollectionViewCell 

     cell.playBtn.tag = indexPath.row 
     cell.playBtn.addTarget(self, action: Selector("buttonAction:"), forControlEvents: .TouchUpInside) 

     return cell 

    } 

目標方法:

func buttonAction(sender:UIButton!) { 
     let storyboard = UIStoryboard(name: "Main", bundle: nil) 
     let controller = storyboard.instantiateViewControllerWithIdentifier("SampleViewController") as! PlayViewController 
     self.navigationController?.pushViewController(controller, animated: true) 
    } 

它的工作對我來說,希望其幫助的

相關問題