iOS单元格添加目标无法正常工作?

时间:2016-05-03 09:59:24

标签: ios objective-c target

在我的应用中,我在UICollectionView cellForRowAtIndexpath中编写了以下代码[CollectionView Cell is a custom cell]

- (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中有四个项目,但是对于第一个项目,只调用此目标方法,其余的甚至不触发原因?

3 个答案:

答案 0 :(得分: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 :(得分: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)
    }

它为我工作,希望它有用

答案 2 :(得分: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);
}