我有一個我正在處理的項目,其中涉及UITabBarController
中的3個選項卡(全部在故事板中完成)。在UITabBarController/UIViewControllers之間移動一個值
每個選項卡運行不同的視圖控制器。
我有一個按鈕在選項卡1上執行計算並在文本框中返回結果。我需要它,當我點擊計算時,結果也會在標籤2中的文本框中返回。
我不太確定如何在UIViewController
之間傳遞數據,因此不勝感激。
我有一個我正在處理的項目,其中涉及UITabBarController
中的3個選項卡(全部在故事板中完成)。在UITabBarController/UIViewControllers之間移動一個值
每個選項卡運行不同的視圖控制器。
我有一個按鈕在選項卡1上執行計算並在文本框中返回結果。我需要它,當我點擊計算時,結果也會在標籤2中的文本框中返回。
我不太確定如何在UIViewController
之間傳遞數據,因此不勝感激。
您可以在應用程序委託中定義一個變量,並將結果存儲在該變量中。一旦你切換了類,你可以通過創建appDelegate的一個實例並將它賦給你的文本字段來在你的類中獲取這個值。
正如Sanjit所說,NSUserDefaults也是一個非常方便和乾淨的方法來實現這一點。
謝謝。
如果您不是真的需要存儲計算值,而只是通知tab2中的其他控制器該值已更改,則可以使用NSNotificationCenter
來發布NSNotification
。
當您在tab2中初始化控制器時,您需要將其添加爲通知的觀察者。
類似的東西:
在TAB1:
NSNumber *value = nil; // the computed value
[[NSNotificationCenter defaultCenter]
postNotificationName:@"com.company.app:ValueChangedNotification"
object:self
userInfo:@{@"value" : value}];
在TAB2:註冊爲觀察者(在init或viewDidLoad中的方法)
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(valueChanged:)
name:@"com.company.app:ValueChangedNotification"
object:nil];
該方法將被調用時,通知已發佈:
- (void)valueChanged:(NSNotification *)note
{
NSDictionary *userInfo = note.userInfo;
NSNumber *value = userInfo[@"value"];
// do something with value
}
別忘了請從觀察員控制器viewDidUnload或更早:
[[NSNotificationCenter defaultCenter] removeObserver:self];
按vshall說,你可以做到這一點的東西像波紋管: -
yourAppdelegate.h
@interface yourAppdelegate : UIResponder <UIApplicationDelegate,UITabBarControllerDelegate>
{
NSString *myCalResult;
}
@property (nonatomic,retain) NSString *myCalResult;
yourAppdelegate。 m
@implementation yourAppdelegate
@synthesize myCalResult,
yourCalclass.h
#import "yourAppdelegate.h"
@interface yourCalclass : UIViewController
{
yourAppdelegate *objAppdelegate;
}
yourCalclass。米
- (void)viewDidLoad
{
objAppdelegate = (yourAppdelegate *) [[UIApplication sharedApplication]delegate];
[super viewDidLoad];
}
-(IBAction)ActionTotal
{
objAppdelegate.myCalResult=result;
}
現在結果存儲在objAppdelegate.myCalResult
您可以在另一個選項卡使用這個變量與創建yourAppdelegat的對象。希望它可以幫助你
你可以使用nsuserdefaults來存儲該值並從nsuserdefaults中獲取它以顯示在標籤2中。希望它能幫助你。 – Exploring
你可以檢查我的答案在這裏:http://stackoverflow.com/questions/14291043/how-to-pass-value-to-another-controller-view-in-xcode/14291197#14291197 – Bhavin
可能重複的[傳遞數據在視圖控制器之間](http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) –