簡體   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