2013-03-20 50 views
0

這是我用過的代碼。IOS中的按鈕操作問題

在View控制器A:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [button setFrame:CGRectMake(50, 50, 70, 40)]; 
    [button setTitle:@"Next View" forState:UIControlStateNormal]; 
    [button addTarget:self action:@selector(nextView) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:button]; 
} 

-(void) nextView 
{ 
    SecondviewController *secondView = [[SecondviewController alloc] init]; 

    [self.view addSubview:secondView.view]; 
} 

在視圖控制器B:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [button setFrame:CGRectMake(50, 50, 70, 40)]; 
    [button setTitle:@"Previous View" forState:UIControlStateNormal]; 
    [button addTarget:self action:@selector(previousView) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:button]; 
} 

-(void) previousView 
{ 

    [self.view removeFromSuperview]; 
} 

問題:當我在視圖控制器B點擊按鈕,它不是切換回視圖控制器A ...

+0

發佈代碼塊時,您需要縮進4個空格才能正確格式化(固定)。 – foundry 2013-03-20 14:15:38

回答

0

你不切換viewControllers,你正在從viewController B的視圖,並添加它作爲一個subv IEW到的v​​iewController A.

這裏:

 SecondviewController *secondView = [[SecondviewController alloc] init]; 
    [self.view addSubview:secondView.view]; 

您需要導航到新視圖控制器 ...這個替換它例如

SecondviewController *secondViewController = [[SecondviewController alloc] init];  
    [self presentViewController:secondViewController animated:YES completion:NIL]; 

(這是最好的,包括'控制器'命名控制器時,以避免與他們的看法混淆)

然後要返回,您需要關閉呈現的v iewcontroller ...

在ViewControllerB替換此:

[self.view removeFromSuperview]; 

隨着

[[self presentingViewController] dismissViewControllerAnimated:YES completion:NIL]; 

這是從呈現的viewController將消息發送回 - 的viewController b - 要呈現的的viewController,viewControllerA這確實實際解僱。

0

而不是將第二個子視圖添加到第一個子視圖,您需要呈現或推動堆棧中的視圖控制器。您只是簡單地將它添加爲子視圖。

SecondviewController *secondView = [[SecondviewController alloc] init]; 
[self presentViewController:secondView animated:NO completion:nil]; 

在第二個視圖控制器中,當您關閉它時,您可以簡單地將它從堆棧中解散/彈出。

[self dismissViewControllerAnimated:YES]; 
+0

嗨AmitApollo ..我通過使用你的代碼解決了這個問題。十分感謝。我在UItextview中有一個查詢。我需要顯示大量的文字作爲描述在我的應用程序中..我已經使用了UItextview這種情況。但我不能滾動查看全文..我的代碼是:desc = [[UITextView alloc] initWithFrame:CGRectMake(10 ,360,300,300)]; desc.text = @「更多沒有行文字在這裏.....」; – Karthik 2013-03-20 14:55:02

+0

調查UIScrollView。應該有大量的文檔讓你開始使用這個控件。 – ApolloSoftware 2013-03-20 14:57:48

+0

好的..好的..謝謝你 – Karthik 2013-03-20 15:06:01