ios - 自定义的UICollectionViewCell 无XIB,for循环创建btn 用代理设置btn的绑定事件无效怎么回事?
怪我咯
怪我咯 2017-04-17 16:38:11
[iOS讨论组]

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

#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);
}
怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
PHP中文网
@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的初始化通常不用这个,用了这个不调父类

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号