开发者

Calling MainViewController method from subview

I have added a subview in my MainViewController. How can i call a method of my MainViewController from my subview开发者_开发百科?


As part of general code-decopeling strategies of MVC, the view should not know about the controller. (Google is your friend if you don't know about MVC, it's important.) If you want interactions with the view to be passed to the controller, you should make a delegate protocol, create a delegate interface, implement it in the controller, and connect the controller to the view's delegate in interface builder. That probably sounds like a lot, so here's an example:

Lets say we have a CalendarView, and we want to tell the controller when someone tapped a date, and ask if we should make that the selected date:

1) Make a delegate protocol

@protocol CalendarViewDelegate
- (BOOL)shouldSelectDate:(NSDate *)tappedDate;
@end

2) Add a (non-retained!) delegate property to CalendarView, as an IBOutlet

@interface CalendarView : UIView
...
@property IBOutlet id<CalendarViewDelegate> delegate;
@end

3) Implement CalendarViewDelegate in whichever controller(s) you need to

MainViewController.h:

@interface MainViewController<CalendarViewDelegate> : UIView

MainViewController.m:

@implementation MainViewController
...
- (BOOL)shouldSelectDate:(NSDate *)tappedDate {
    //Whatever logic you want here 
    //the view should only be doing UI stuff, everything else goes here
}

@end


in subviewcontroller implementation

import "urmainViewcontrollerclassname"

urmainViewcontrollerclassname *temp=(urmainViewcontrollerclassname*)self.parentViewController;

[temp mainVCFunction];

    //test with nslog in mainVCFunction.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜