objective-c 协议和委托(转)
objective-c protocol delegate
@protocol UIBViewDelegate <NSObject>
@optional
- (void)ontouch:(UIScrollView *)scrollView;//声明协议方法
@end
@interface BView : UIScrollView<UIScrollViewDelegate>
{
id< UIBViewDelegate > _touchdelegate;//设置委托变量
}
@property(nonatomic,assign) id< UIBViewDelegate > _touchdelegate;
@end
B_View.mm:
@synthesize _touchdelegate;
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
_touchdelegate=nil;
}
return self;
}
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
[super touchesBegan:touches withEvent:event];
if(_touchdelegate!=nil && [_touchdelegate respondsToSelector: @selector(ontouch:) ] == true)
[_touchdelegate ontouch:self];//调用协议委托
}
@interface AViewController : UIViewController < UIBViewDelegate >
{
BView *m_BView;
}
A_View.mm:
- (void)viewWillAppear:(BOOL)animated
{
m_BView._touchdelegate = self;//设置委托
[self.view addSubview: m_BView];
}
- (void)ontouch:(UIScrollView *)scrollView
{
//实现协议
}