将值从一个TabBar控制器传递到另一个Controller并设置值。
我有5个UIViewcontroller,它被添加到UITabBarController。
controller1 = new Controller1();
controller2 = new Controller2();
controller3 = new Controller3();
controller4 = new Controller4();
controller5 = new Controller5();
controller1.TabBarItem = new UITabBarItem ("first", UIImage.FromFile("/Images/first.png"), 0);
controller5.TabBarItem = new UITabBarItem ("second", UIImage.FromFile("/Images/four.png"), 1);
controller5.TabBarItem = new UITabBarItem ("third", UIImage.FromFile("/Images/four.png"), 2);
controller5.TabBarItem = new UITabBarItem ("four", UIImage.FromFile("/Images/four.png"), 3);
controller5.TabBarItem = new UITabBarItem ("five", UIImage.FromFile("/Images/four.png"), 4);
var tabs = new UIViewController[] {
controller1, controller2, controller3, controller4, controller5
};
ViewControllers = tabs;
controller1有标签
UILabel lbl_Label1;
string setValue = "Welcome";
lbl_Label1.Text = setValue;
来自controller3的更改controller1标签值
从Controller1创建对象并设置标签文本。
Controller1 controller1 = new Controller1();
controller1.lbl_Label1.Text = "Bye";
this.TabBarController.SelectedIndex = 0;
哪个不行。它为controller1的标签显示相同的Welcome
消息。
答案 0 :(得分:0)
它不起作用,因为您创建了另一个Controller1实例。
通常,我喜欢在这种情况下使用通知,试试这个:
如果要更改文本标签,请在Controller3中添加此代码:
NSDictionary dict = [NSDictionary dictionaryWithObject:@"new label text"
forKey:@"newText"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"changeTextLabel" object:nil userInfo:dict];
这是在Controller1的viewDidLoad中
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTextLabelMethod:) name:@"changeTextLabel" object:nil];
当您从Controller3发送通知时,Controller1调用方法“changeTextLabelMethod”,您可以执行所需的一切:
例如,在Controller1中:
-(void) changeTextLabelMethod:(NSNotification *) notification{
NSDictionary *dict = [notification userInfo];
lbl_Label1.Text = [dict objectForKey:@"newText"];
}
答案 1 :(得分:0)
虽然通知可行,但有一种更简单的方法:
您可以通过调用tabBarController - >来访问标签栏中的viewControllers。 viewControllers。
所以:
this.tabBarController.viewControllers
应该为您提供一组viewControllers。如果您尝试根据另一个viewController中发生的事情修改第一个视图控制器,您可以这样做:
Controller1 *myController1Instance = (Controller 1 *) this.tabBarController.viewControllers[0];
myController1Instance.lbl_Label1.Text = "Bye";
this.TabBarController.SelectedIndex = 0;
假设lbl_Label1是Controller1上的公共属性。