0

我正在使用UICollectionView我为我的“单元格”类创建的,我CustomCell在其中实例化了一个按钮。如果我将操作放在“ CustomCell.m”中,则会响应日志并给我写一些东西,但我需要在我的类中使用包含UICollectionView.

由于这个原因,我使用它的代表,但仍然不工作。

我该如何解决?

这是我添加到 CustomCell.h 的代码:

@class CustomCell;

@protocol CustomCellDelegate
- (void)btnSaveColor:(CustomCell *)sender;
@end

@interface CustomCell : UICollectionViewCell

@property (nonatomic, assign) id delegate;

@property (strong, nonatomic) IBOutlet UILabel *lblCustomCell;
@property (strong, nonatomic) IBOutlet UIView *bgCustomCell;
@property (strong, nonatomic) IBOutlet UILabel *RCustomCell;
@property (strong, nonatomic) IBOutlet UILabel *GCustomCell;
@property (strong, nonatomic) IBOutlet UILabel *BCustomCell;
- (IBAction)btnSaveColor:(id)sender;

@end

这是我添加到 CustomCell.m 的代码

#import "CustomCell.h"

@implementation CustomCell

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (IBAction)btnSaveColor:(CustomCell *)sender {
    [_delegate btnSaveColor:self];
}

@end

这是在 ViewController.h 中输入的代码

#import <UIKit/UIKit.h>
#import "ViewController.h"
#import "CustomCell.h"

@interface gradientViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, CustomCellDelegate>

@property (nonatomic, strong) NSString *hexCode;
@property (strong, nonatomic) IBOutlet UILabel *lblDest;
@property (strong, nonatomic) IBOutlet UICollectionView *gradientCollectionView;
@property (strong, nonatomic) NSArray *gradientArray;
@property (strong, nonatomic) NSArray *gradientArrayToWhite;
@property (strong, nonatomic) NSArray *allGradient;

@property (strong, nonatomic) NSArray *reverse;
@property (strong, nonatomic) NSArray *sorted;

@property (strong, nonatomic) IBOutlet UIView *bgHEXColorGradient;
- (IBAction)btnBack:(id)sender;
@property (strong, nonatomic) IBOutlet UIButton *bgBack;

@property (nonatomic, strong) NSArray *ColorSchemeAnalagous;
@property (nonatomic, strong) NSArray *ColorSchemeComplementary;
@property (nonatomic, strong) NSArray *ColorSchemeTriad;

@end

这个在 ViewController.m

#import "gradientViewController.h"
#import "ViewController.h"
#import "UIColor+Expanded.h"
#import "CustomCell.h"
#import <QuartzCore/QuartzCore.h>
#import "ColorUtils.h"
#import "MPColorTools.h"
#import "RecipeCollectionHeaderView.h"
#import "UIColor+Colours.h"

@interface gradientViewController ()

@end

@implementation gradientViewController

- (void)btnSaveColor:(CustomCell *)sender {
    NSLog(@"Funziona il delegato!");
}
4

1 回答 1

0

替换这行代码:

@property (nonatomic, assign) id delegate;

有了这个:

@property (nonatomic, weak) id<CustomCellDelegate> delegate;

我也设置了 weak like 属性,因为使用 assign 你有一个强大的对象,UICollectionView然后你的 Cell 不能被释放

于 2013-10-11T14:35:30.927 回答