2012-10-21 30 views
0

所以我有我的應用程序,我有一個帶水龍頭計數器和顯示標籤的視圖。我希望它在主視圖(現在它)上顯示文本,但也在第二個視圖上顯示。從兩個視圖上的水龍頭計數器顯示文字

那麼我怎麼能在另一個視圖上顯示文本。如果需要更多的細節,請發郵件

重現步驟FOR TAP計數器 .h文件:

@interface Level1 : UIViewController { 

int counter; 

IBOutlet UILabel *count; 

} 

-(IBAction)plus; 

@property (assign) int counter; 

@end 

.m文件:

@synthesize counter; 

- (void) viewDidLoad { 

counter=1; 

count.text = @"0"; 

[super viewDidLoad]; 
} 

-(IBAction)plus { 

counter=counter + 1; 

count.text = [NSString stringWithFormat:@"%i",counter]; 
} 

@end 

在此先感謝

回答

1

您可以用計數器的值創建模型這將在兩種觀點中共享。

模型通常使用單例模式創建。在這種情況下,這是可以做到這樣:

您的.h文件中:

@interface CounterModel 
@property (assign) NSInteger counter;// atomic 
+ (id)sharedInstance; 
- (void)increment; 
@end 

您的.m文件:

@implementation CounterModel 
@synthesize counter; 

- (id)init 
{ 
    if (self = [super init]) 
    { 
    } 
    return self; 
} 

+ (id)sharedInstance 
{ 
    static CounterModel *instance = nil; 
    if (instance == nil) 
    { 
     instance = [[CounterModel alloc] init]; 
    } 
    return instance; 
} 

- (void)increment 
{ 
    counter++; 
} 

@end 

然後從一個視圖控制器,你可以撥打:

[[CounterModel sharedInstance] increment]; 

從第二位您可以通過撥打電話讀取此更新值:

[[CounterModel sharedInstance] counter]; 

爲了實現你想要的,你可以在viewWillAppear方法中設置從模型計數器值中讀取的UILabel值。

+0

我不太認同,你可以Skype我解釋一下。 –

+0

Kyle Greenlaw .. –

+0

請指出您確切無法理解的內容,以便我可以對此發表評論。基本上我提到的模型將會是你的新課堂。請閱讀模型視圖控制器[鏈接](https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaDesignPatterns/CocoaDesignPatterns.html#//apple_ref/doc/uid/TP40002974-CH6 -SW1)瞭解這種方法。 –

0

在這裏,您可以使用委託將數據傳遞給另一個視圖。當您通過第一個視圖加載第二個視圖時,可以將第一個視圖設置爲數據源。

http://www.youtube.com/watch?v=e5l0QOyxZvI

您也可以使用通知中心發送信息到其他視圖。

相關問題