我遇到了一个小问题(毫不奇怪,因为我刚刚开始使用 xcode)。我尝试用 if 语句来解决这个问题,但它们显然是错误的方法。
这就是我想要做的:在第一个 ViewController 中,我有 4 个按钮。如果用户按下第一个按钮,他将进入 ViewController2 并且标签显示“您按下了第一个按钮”。如果用户按下第二个按钮,他将进入 ViewController2,并且标签显示“您按下了第二个按钮”,依此类推。
我尝试用标签语句来解决它,例如: FirstViewController.m
- (IBAction)switch:(id)sender;
{
UIButton *buttonPressed = (UIButton *)sender;
SecondViewController *second =[[SecondViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:second animated:YES];
second.buttonTag = buttonPressed.tag;
[self.navigationController pushViewController:second animated:YES];
(button.tag = 9001);
- (IBAction)switch2:(id)sender2;
{
UIButton *buttonPressed = (UIButton *)sender2;
SecondViewController *third =[[SecondViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:third animated:YES];
second.buttonTag = buttonPressed.tag;
[self.navigationController pushViewController:third animated:YES];
(button2.tag = 9002);
这是我在 SecondViewController.m 中所做的
- (void)viewDidLoad
{
[super viewDidLoad];
if (buttonTag == 9001) {
self.label1.text = [[NSString alloc] initWithFormat:@"Radnomtext"];
self.label2.text = [[NSString alloc] initWithFormat:@"Randomtext"];
self.label3.text = [[NSString alloc] initWithFormat:@"Randomtext?"];
if (buttonTag == 9002) {
self.label1.text = [[NSString alloc] initWithFormat:@"Radnomtext2"];
self.label2.text = [[NSString alloc] initWithFormat:@"Randomtext2"];
self.label3.text = [[NSString alloc] initWithFormat:@"Randomtext2?"];
他总是给我 ButtonTag 9001 的标签 - 有人知道为什么吗?
最佳答案
这里有一个方便您使用的小技巧:标签。
每个UIView
都可以有一个属性标签
。它是一个简单的整数,您可以在代码 (button.tag = 456;
) 或 Interface Builder 中分配它。在您的 switch
方法中,只需使用:
-(IBAction)switch:(id)sender {
UIButton *buttonPressed = (UIButton *)sender;
// create the second view controller, e.g.
SecondViewController *secondViewController = [[SecondViewController alloc] init];
// it should have an NSInteger @property e.g. "buttonTag"
secondViewController.buttonTag = buttonPressed.tag
[self.navigationController
pushViewController:secondViewController animated:YES];
// if not using ACT: [secondViewController release];
}
所以只是为了确保:你的陈述
it is a no go to pass properties or values from one to another view controller
完全错误。如果新的 View Controller 有一个@property(您在.h
文件中定义,在.m
文件中定义@synthesize
) ,您可以在推送新的 View Controller 之前简单地分配这些属性。这就是我们在上面的代码片段中所做的。
关于ios - 两个 ViewController - 第一个有 x 个按钮,第二个有 x 个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8777548/