oc之mac中NSView的时间相应

mac开发系列17:定制NSView的事件处理

2017.08.14 11:39* 字数 399 阅读 217评论 0

这里以鼠标左击,即mouseDown为例。

我们通常的做法是,实现一个NSView的子类,例如mac微信中的MMView,然后在子类中重写mouseDown函数,再在mouseDown函数里面实现自己的事件处理逻辑。

不过,有些场景需要我们在此基础上做更加灵活的定制:MMView实际上是作为公共UI控件(一般会是NSWindow或者NSView的属性/成员变量),不同NSWindow/NSView中的事件处理逻辑是不一样的,而且这样的NSWindow/NSView会随着业务需要不断增加。这就意味着,不可能在MMView的mouseDown中穷举所有的事件处理逻辑(即使可以,也不应该在公共控件中耦合过多的业务逻辑)。

我们可以让mouseDown只负责事件捕捉以及事件传递(通过block来传递),事件处理交给具体的NSWindow/NSView来实现,代码实现如下:

1、在MMView中定义:

@property (nonatomic, copy) void (^mouseDownInsideBlock)(NSEvent *theEvent); // 这个block用于接受mouseDown传递过来的event

  1>(void)setMouseDownInsideBlock:(void (^)(NSEvent *))mouseDownInsideBlock; // block的set函数
  2>、MMView中的mouseDown函数捕捉事件,并通过block传递:

(void)mouseDown:(NSEvent *)theEvent {

if (self.mouseDownInsideBlock) {
NSPoint aPoint = [self convertPoint:[theEvent locationInWindow] fromView:nil];
if (!NSPointInRect(aPoint, self.bounds)) {
return;
}
// Call back
self.mouseDownInsideBlock(theEvent); // 事件传递

} else {
[super mouseDown:theEvent];
}
}
3、NSWindow/NSView中接受mouseDown传递过来的事件,并做所需的事件处理:

@weakify(self)
[self.sendToFriendContainer setMouseDownInsideBlock:^(NSEvent *theEvent) {
@strongify(self)
[self onClickSendToFriend]; // 事件处理
}];

猜你喜欢

转载自www.cnblogs.com/sundaymac/p/10335450.html