Obj-C,iOS,我如何编写/使用包含 touchesBegan 和 touchesMoved 等的标准类? [英] Obj-C, iOS, how do I write / use a standard class which will contain touchesBegan and touchesMoved etc?

查看:48
本文介绍了Obj-C,iOS,我如何编写/使用包含 touchesBegan 和 touchesMoved 等的标准类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将在多个视图中使用与视图控制器相同的代码,我不想将代码粘贴到每个视图中.

I'm going to be using the same code that I have in my view controller in several views and I don't want to have to paste the code into each.

有人可以向我展示几行代码,向我展示如何做到这一点吗?

Can someone show me a few lines of code showing me how to do this ?

我猜我将不得不在界面中声明一个类的实例,并为我将要进行子类化的每个触摸功能放一个回手方法?

I'm guessing i'm going to have to declare an instance of the class in the interface and put a hand back method for each of touch functions I'll be sub classing ?

推荐答案

如果我正确理解了这个问题,您希望从您的每个视图中为 touchesBegan、touchesMoved... 执行相同的代码.

If I understand the question correctly you want the same bit of code executed for touchesBegan, touchesMoved... from each of your views.

我这样做的方法是使用委托模式.

The way I would do this would be using the delegate pattern.

@protocol ViewTouchDelegate
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
@end

@interface ViewA : UIView {
    id <ViewTouchDelegate> touchDelegate;
}

@implementation ViewA
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self->touchDelegate touchesBegan:touches withEvent:event];
}
@end // End View A

@interface ViewB : UIView {
    id <ViewTouchDelegate> touchDelegate;
}

@implementation ViewB
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self->touchDelegate touchesBegan:touches withEvent:event];
}
@end // End View B

这将让您将所有触摸处理代码放在一个地方(在一个符合 ViewTouchDelegate 协议的类中),并将该委托分配给您的每个视图.

This will let you put all your touch handling code in one place (in a class that conforms to the ViewTouchDelegate protocol), and give that delegate to each of your views.

在我的示例中,我将 touchesBegan 的签名与 UIResponder 的 touchesBegan 相同,但您可以根据自己的需要进行定制.

In my example I have made the signature of touchesBegan the same as UIResponder's touchesBegan, but you can tailor it to your needs.

示例 ViewTouchDelegate

Example ViewTouchDelegate

@interface MyViewTouchDelegate : NSObject <ViewTouchDelegate>
@end

@implementation MyViewTouchDelegate
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //put all your common touch handling code in here
}
@end

根据您的目的在 ViewTouchDelegate 协议中定义您需要的任何其他方法,例如 touchesMoved、touchesEnded、yourOwnCustomEvent.

Define any additional methods you need in the ViewTouchDelegate protocol for your purposes, for example touchesMoved, touchesEnded, yourOwnCustomEvent.

这篇关于Obj-C,iOS,我如何编写/使用包含 touchesBegan 和 touchesMoved 等的标准类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆