能否提供一些UIViewController
之间一对一事件传递的例子和形式化模式?我认为NSNotificationCenter
不适用于此用例,因为它基于事件总线和广播模式,用于广泛的状态更改,这就是为什么应该用于一对多传输。我知道KVO
在这种情况下根本不适用,因为它通常用于经典MVC
领域中模型和控制器层之间的通信。所以现在我只知道一对一事件传输的一种方式:委托模式。但也许还有更优雅的simple
而不是easy
的解决方案。
例如:
在视图中,动作被发送到:
@protocol MapViewDelegate <NSObject>
@required
-(void)MapImageButtonClicked:(UIButton*)sender;
@end
@interface MapView : UIView
{
UIButton *mapButton;
id mapViewDelegate;
}
@property(nonatomic,retain) id mapViewDelegate;
@property(nonatomic,retain) UIButton *mapButton;
。m
[mapButton addTarget:self.delegate action:@selector(mapImageButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
在视图中,动作将从:
发送#import "MapView.h"
@interface MapViewController : UIViewController<MapViewDelegate>
{
}
.m
MapView *map = [[MapView alloc] init];
map.delegate = self;
-(void)MapImageButtonClicked:(UIButton*)sender
{
//implement the necessary functionality here
}
希望你能明白。
你可以把这个方法放在视图接口的协议中:
@protocol MyViewWithButtonDelegateProtocol<NSObject>
-(void)myButtonAction:(id)sender; @end
- 你在视图中放了一个NSObject或UIView类型的新属性叫做delegate
- 你让你的视图去处理那个动作并在它初始化视图时将委托属性赋值给自我。
- 你在你的视图控制器实现中实现myButtonAction。
- 现在你只需做[myButton setTarget:delegate]行动:@ selector (myButtonAction:)forControlEvents: UIControlEventTouchUpInside];。