自定义的UICollectionViewCell 无XIB,for循环创建btn 用代理设置btn的绑定事件无效怎么回事?

我用了代理 为什么点击事件没作用?

#import <UIKit/UIKit.h>
#import "AFNetWorkingTool.h"


@protocol FristSectionCollectionViewCellDelegate <NSObject>

@required
-(void)choseTerm:(UIButton *)button;
-(void)changeButtonBackgroundColor:(UIButton *)button;
@end


@interface FristSectionCollectionViewCell : UICollectionViewCell

@property(nonatomic,strong)UIButton *eight;

@property(nonatomic,assign)id<FristSectionCollectionViewCellDelegate> delegate;
-(void)eight_btn_click:(UIButton *)btn;

@end




#import "FristSectionCollectionViewCell.h"


@implementation FristSectionCollectionViewCell
-(id)initWithFrame:(CGRect)frame{

     
        for (int i = 0; i <8; i ++) {
            _eight_btn = [UIButton buttonWithType:UIButtonTypeCustom];
            _eight_btn.tag = i;
            _eight_btn.frame = CGRectMake(坐标);
            [self.contentView addSubview:_eight_btn];

                
  
            [self.eight_btn addTarget:self action:@selector(eight_btn_click:) forControlEvents:UIControlEventTouchUpInside];

            }
            }
            
            
-(void)eight_btn_click:(UIButton *)btn{
    if ([_delegate respondsToSelector:@selector(choseTerm:)]) {
        [_delegate choseTerm:btn];
    }
}

#import "MainViewController.h"
@interface MainViewController ()

-(void)choseTerm:(UIButton *)button{
                    NSLog(@"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  %ld",(long)button.tag);
}
阅读 3.9k
2 个回答
@interface MainViewController () <FristSectionCollectionViewCellDelegate>

......

self.fristSectionCollectionViewCell.delegate = self;

虽然你实现了delegate相应的方法,但如果你不给delegate赋值,那么,如下的判断将为false:

if ([_delegate respondsToSelector:@selector(choseTerm:)]) 

Update

你的工程我始终跑不起来,缺少很多image
所以我自己做了个demo,delegate方法是可以调用到的,和你的代码相对比,实在找不出差别。
你跑跑这个demo测试下吧。
https://github.com/li2/Learning_iOS_Programming/tree/master/CollectionViewButtonDelegateTest

cell的初始化通常不用这个,用了这个不调父类

推荐问题
宣传栏