开发者

Sending messages from subview to superview in Cocoa, UIResponder?

I have all these subview which are touch sensitive, I want to send a message from the subview to the superview, to say that a user selected it, so the superview can communicate with the rest of the controller.

I can not co开发者_如何学JAVAmmunicate between the subviews and the controllers, subviews >> superview >> controller

Perhaps use, UIResponder to achieve this?


Depending on the subviews, the target/action mechanism can be good for this. If you can derive your subviews from UIControl, then it's particularly easy to have your subviews send their action message to their target, which is usually your view controller. You'll be able to lay out your views in Interface Builder and specify their target and action by connecting them to the view controller. If you can't derive them from UIControl for some reason, then you'd have to implement the equivalent of target/action and you won't have the same support in IB, but it's still pretty straightforward.

Another possibility is to let the view controller do the touch handling for all the subviews. This is basically taking advantage of the responder chain as you suggested, but at the touch-handling level. It may not be ideal if there are a lot of subviews to keep track of, but it's workable.

A third way to do it is to have your subviews post a notification when they're selected.

As is, UIResponder doesn't provide a mechanism for passing arbitrary messages along the responder chain. I'm not sure that adding that capability is the most elegant way to send a message specifically from a subview to the view controller. There are potentially many intermediate objects between the view controller and the subviews, and involving the entire chain when you already know where you want the message to go seems wrong. However, it's interesting to think about extending UIResponder to make the responder chain a conduit for more than just events. You could add a category to UIResponder:

@interface UIResponder (Messages)
- (void)sendMessage:(SEL)message withObject:(id)object;
@end;

@implementation UIResponder (Messages)
- (void)sendMessage:(SEL)message withObject:(id)object
{
    if ([self respondsToSelector:message]) {
        [self performSelector:message withObject:object];
    }
    else {
        [[self nextResponder] sendMessage:message withObject:object];
    }
}
@end

WARNING The code above is completely untested, and may be a lousy idea for reasons I haven't yet thought of. Proceed with caution. Expect compilation errors. Cross your fingers. Please let me know if it works out well, and leave me alone if it doesnt.


Why can't you use [self.superview sendMessage]?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜