@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]; //调用协议委托
}
@end
A_View.h:
@interface AViewController : UIViewController < UIBViewDelegate >
{
BView *m_BView;
}
@end
A_View.mm:
- (void)viewWillAppear:(BOOL)animated
{
m_BView._touchdelegate = self; //设置委托
[self.view addSubview: m_BView];
}
- (void)ontouch:(UIScrollView *)scrollView
{
//实现协议
}
本文介绍了一个使用Objective-C实现的iOS应用中触摸事件处理的方法。通过定义一个触摸事件的代理协议,让UIScrollView能够通知其代理对象(通常是视图控制器)触摸事件的发生。此方式有助于解耦视图和视图控制器,使代码更易于维护。
384

被折叠的 条评论
为什么被折叠?



