iphone - 编写可重用接口(interface)对象的正确技术?

标签 iphone objective-c oop widget

我正在寻找编写自己的接口(interface)对象的正确方法。

比如说,我想要一个可以双击的图像。

@interface DoubleTapButtonView : UIView {
    UILabel *text;
    UIImage *button;
    UIImage *button_selected;
    BOOL selected;
}
// detect tapCount == 2
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

这工作正常 - 按钮接收事件并可以检测双击。

我的问题是如何干净利落地处理 Action 。我尝试过的两种方法是添加对父对象的引用和委托(delegate)。

传递对父对象的引用非常简单...

@interface DoubleTapButtonView : UIView {
    UILabel *text;
    UIImage *button;
    UIImage *button_selected;
    BOOL selected;
    MainViewController *parentView; // added
}

@property (nonatomic,retain) MainViewController *parentView; // added

// parentView would be assigned during init...
- (id)initWithFrame:(CGRect)frame 
     ViewController:(MainViewController *)aController;

- (id)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

但是,这会阻止我的 DoubleTapButtonView 类被轻松添加到其他 View 和 View Controller 。

委托(delegate)为代码添加了一些额外的抽象,但它允许我在任何适合委托(delegate)接口(interface)的类中使用 DoubleTapButtonView。

@interface DoubleTapButtonView : UIView {
    UILabel *text;
    UIImage *button;
    UIImage *button_selected;
    BOOL selected;
  id <DoubleTapViewDelegate> delegate;
}

@property (nonatomic,assign) id <DoubleTapViewDelegate> delegate;

@protocol DoubleTapViewDelegate <NSObject>

@required
- (void)doubleTapReceived:(DoubleTapView *)target;

这似乎是设计对象的正确方法。该按钮只知道它是否被双击,然后告诉委托(delegate)人决定如何处理此信息。

我想知道是否还有其他思考这个问题的方法?我注意到 UIButton 使用 UIController 和 addTarget: 来管理发送事件。在编写我自己的接口(interface)对象时是否希望利用该系统?

更新:另一种技术是使用 NSNotificationCenter 为各种事件创建观察者,然后在按钮中创建事件。

// listen for the event in the parent object (viewController, etc)
[[NSNotificationCenter defaultCenter] 
  addObserver:self selector:@selector(DoubleTapped:) 
  name:@"DoubleTapNotification" object:nil];

// in DoubleTapButton, fire off a notification...
[[NSNotificationCenter defaultCenter] 
  postNotificationName:@"DoubleTapNotification" object:self];

这种方法有什么缺点?更少的编译时检查,以及潜在的带有事件在对象结构之外飞来飞去的意大利面条代码? (如果两个开发人员使用相同的事件名称,甚至命名空间冲突?)

最佳答案

委托(delegate)绝对是去这里的方式。

关于iphone - 编写可重用接口(interface)对象的正确技术?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/480604/

相关文章:

c++ - 带有构建参数的 Monotouch Linea Pro SDK 问题

iphone - 如何在将最终分发版本提交给 iPhone 应用商店进行审核之前对其进行测试?

iphone - xcode 自动创建文件夹(如果不存在)

ios - 将委托(delegate)和数据源设置为 UITableView

iphone - 提交 App Store 后出现无效二进制错误

java - 如何获取 ArrayList 中存储对象的属性值

iphone - 在 SQLite 中保存数组的最佳方法是什么?

iphone - AFNetworking 预期内容类型错误

java - 在父类中使用有关子类的方法是一种不好的做法吗?

java - switch 语句在这里是否合适,采用枚举?