繁体   English   中英

将子视图添加到子视图,但来自另一个类

[英]Add subviews to subview, but from another class

我有一个名为FirstController的ViewController,它具有3个按钮,每次触摸其中一个按钮时,都会打开SecondController(我的另一个ViewController)。 但是,即使所有这三个按钮都打开了相同的ViewController,我也不希望ViewController完全相同,但是根据所按下的按钮,其中的对象将有所不同。 我在SecondController中有一个ScrollView,并且我想根据按下的按钮将不同的图像作为子视图添加到ScrollView中。

这是到目前为止我得到的:


#import "FirstController.h"
#import "SecondController.h"

@interface Level1 ()

@end

@implementation FirstController

- (IBAction) button1 {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
SecondController *ViewForButton1 = [mainStoryboard instantiateViewControllerWithIdentifier:@"View2"];
}
- (IBAction) button2 {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
SecondController *ViewForButton2 = [mainStoryboard instantiateViewControllerWithIdentifier:@"View2"];
}
- (IBAction) button3 {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
SecondController *ViewForButton3 = [mainStoryboard instantiateViewControllerWithIdentifier:@"View2"];
}

@end

我知道如何将图像添加为孔视图的子视图,但是我需要它在ScrollView中! 我现在如何实现ScrollView到此类并向其添加子视图?

PS:我有3个以上的按钮,但在此示例中仅使用3个。

Tag分配给每个UIButton并在点击按钮时获取标签,然后将此标签传递到YourSecondViewController并放置条件,要根据其点击按钮显示要显示的图像。

编写方式,mainStoryboard对象全部实例化,并且作用域仅在创建它们的单个方法内。 您的ViewForButton_对象也是如此。 它们具有不同名称的事实是无关紧要的。

仅凭这一事实,这便使它们彼此成为不同的对象。 它们可以具有自己的内部状态,该内部状态不同于同一类的任何其他对象。

更新

在每个按钮方法中尝试以下方法:

- (IBAction) button1 {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
SecondController *ViewForButton1 = [mainStoryboard instantiateViewControllerWithIdentifier:@"View2"];
... create views to add to the second view controller here
... add he views that you created to the second view controller

}

在某个时候,我想您想显示与第二个视图控制器关联的视图。 我将由您自己决定,但我假设您将使用相同的方法来执行此操作。

顺便说一句,这本身与AppDelegate无关。

我建议以另一种方式来做到这一点。 应该在SecondController内部的viewDidLoad方法中将不同的视图放入滚动视图。 要将项目添加到滚动视图,您将需要IBOutlet到该滚动视图,并且当您首次从FirstController实例化控制器时,尚未设置该设置。 因此,我只有一个按钮方法,并用它来实例化SecondController,并在其中设置一个属性(在我的示例中称为buttonTag),该属性取决于所按下按钮的标记。

-(IBAction)goToSecondController:(UIButton *)sender {
    SecondController *second = [self.storyboard instantiateViewControllerWithIdentifier:@"Next"];
    second.buttonTag = sender.tag;
    [self.navigationController pushViewController:second animated:YES];
}

然后在SecondController中,在switch语句中使用该属性添加所需的内容:

- (void)viewDidLoad {
    [super viewDidLoad];

    switch (self.buttonTag) {
        case 1:
            [self.scrollView addsubview:someView];
            break;
        case 2:
            [self.scrollView addsubview:someOtherView];
            break;
        case 3:
            [self.scrollView addsubview:anotherView];
            break;
        default:
            break;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM