【发布时间】:2015-05-17 05:43:24
【问题描述】:
我为 UIView 设置了一个非常简单的委托。但是,当我尝试这样做时:
if ([self.delegate respondsToSelector:@selector(selectedPlayTrailer:)]){
[self.delegate selectedPlayTrailer:self];
}
我的 self.delegate 为空。我检查了设置为委托的类是正确的:
- (void)setDelegate:(id<MyViewDelegate>)delegateClass
{
// Whether I overwrite this method or not, it's still null.
NSLog(@"%@", delegate);
_delegate = delegateClass;
}
而且它是正确的。但是当它在我的 IBAction 中被调用时 - 它是空的。
编辑:澄清一下,我只是将其放入以查看传入的内容。如果我不覆盖此方法,它仍然为空。
我的代码:
MyView.h
#import <UIKit/UIKit.h>
@class MyView;
@protocol MyViewDelegate <NSObject>
@optional
- (void) myDelegateMethod:(MyView *)sender;
@end
@interface MyView : UIView
@property (nonatomic, weak) id <MyViewDelegate> delegate;
- (IBAction)myButton:(id)sender;
@end
MyView.m
@implementation MyView
@synthesize delegate;
- (id)init
{
if (!(self = [super init])) return nil;
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"MyView"
owner:self
options:nil];
return self;
}
- (IBAction)myButton:(id)sender
{
// NOTE: Here, self.delegate is null
if ([self.delegate respondsToSelector:@selector(myDelegateMethod:)]){
[self.delegate myDelegateMethod:self];
}
}
@end
MyCollectionViewCell.m
#import "MyCollectionViewCell.h"
#import "MyView.h"
@interface MyCollectionViewCell() <MyViewDelegate>
@property (nonatomic, strong) MyView *myView;
@end
@implementation MyCollectionViewCell
@synthesize myView;
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self){
[self setup];
}
return self;
}
- (void)setup
{
self.myView = [MyView new];
self.myView.frame = CGRectMake(0,0,self.bounds.size.width, self.bounds.size.height);
self.myView.alpha = 0.0;
self.myView.layer.cornerRadius = 5.0f;
self.myView.layer.masksToBounds = YES;
self.myView.delegate = self;
[self addSubview:self.myView];
}
// The delegate method
- (void)myDelegateMethod:(MyView *)sender
{
NSLog(@"This is never called...");
}
@end
【问题讨论】:
-
代理是否有可能被释放?尝试将委托属性从弱更改为分配并打开僵尸 - 看看你是否收到错误。
-
initWithFrame 被调用?
-
@Paulw11 尝试但没有错误,仍然为空。还尝试将其设置为强(我知道您通常不应该使用委托属性),但这也无济于事。
-
@Selvin 是的。视图已正确添加,没有错误,但在我调用 IBAction 时委托已失效。
-
尝试将 ViewController 设置为委托而不是 collectioviewcell
标签: ios objective-c xcode delegates