2014-10-02 98 views
0

我有一個類,其子類UITableViewController。根據此類中識別的用戶操作,我需要在表中實例化UIViewController時調用表中的方法。我無法弄清楚如何做到這一點。不同類別的調用方法

我試圖讓這個函數成爲靜態的,但是這不起作用,因爲有一個我需要的實例變量。我大概可以使用NSNotificationCenter,但我的直覺是有更好的方法。有人可以幫忙嗎?謝謝!

MonthsTableViewController.h

@interface MonthsTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate> 
{ 
    NSArray *monthsArray; 
} 
@end 

MonthsTableViewController.m

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { 
    NSLog(@"calling the UIViewController"); 
    //this is where I am stuck!!! 
} 

SubscribeViewController.h

@interface SubscribeViewController : UIViewController <SIMChargeCardViewControllerDelegate> 
{ 
    MonthsTableViewController *monthsController; 
    IBOutlet UITableView *monthsTable; 
} 

- (void) snapMonthsToCenter; 

@end 

SubscribeViewController.m

- (void) snapMonthsToCenter { 
    // snap the table selections to the center of the row 
    NSLog(@"method called!"); 
    NSIndexPath *pathForMonthCenterCell = [monthsTable indexPathForRowAtPoint:CGPointMake(CGRectGetMidX(monthsTable.bounds), CGRectGetMidY(monthsTable.bounds))]; 
    [monthsTable scrollToRowAtIndexPath:pathForMonthCenterCell atScrollPosition:UITableViewScrollPositionMiddle animated:YES]; 
} 
+0

發送通知或定義在'MonthsTableViewController'的協議和委託。然後'MonthsTableViewController'可以告訴它的代表發生了什麼事。 SubscriberViewController可以是委託。當調用委託方法時,'SubscribeViewController'可以調用它自己的'snapMonthsToCenter'或其他任何需要做的事情。 – rmaddy 2014-10-02 03:26:21

回答

0

基本上爲了做到這一點,你需要從你的UITableViewController引用你的UIViewController。這將允許你調用這個對象的方法。通常,您會將此屬性稱爲delegate,因爲您將「父級」UIViewController分配爲「子級」UITableViewController的委託。

修改您的UITableViewController(MonthsTableViewController.h)添加一個委託財產,像這樣:

@interface MonthsTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate> 
{ 
    NSArray *monthsArray; 
    id delegate; 
} 

@property (nonatomic, retain) id delegate; 

@end 

您需要@synthesize.m文件的屬性。如果你還沒有,你還需要在這裏輸入SubscribeViewController.h

然後,當你實例化你的MonthsTableViewController,設置委託到當前的對象MonthsTableViewController像這樣:

MonthsTableViewController *example = [[MonthsTableViewController alloc] init.... // This is the line you should already have 
[example setDelegate:self]; // Set this object's delegate property to the current object 

現在,你必須從你的MonthsTableViewController訪問父SubscribeViewController。那麼你怎麼稱呼功能呢?簡單!您可以硬編碼的方法調用,或者是超級安全,使用respondsToSelector:

[(MonthsTableViewController*)[self delegate] snapMonthsToCenter]; 

在你的情況,上面的代碼是精絕,因爲你知道,這種方法將總是這個對象上存在。但是,通常情況下,代表被聲明爲可能具有可選方法的協議。這意味着雖然方法在@interface中聲明,但它們可能實際上並不存在(被實現)在對象中。在這種情況下,下面的代碼將被用來確保該方法實際上可以在對象上被調用:

if([[self delegate] respondsToSelector:@selector(snapMonthsToCenter)]) { 
    [[self delegate] snapMonthsToCenter]; 
} 
+0

非常感謝。這很棒! – Alex 2014-10-02 04:12:07

相關問題