2015-08-24 59 views
0

我有一個應用程序的工作,我想用另一個UIControllerView調用一個UIControllerView的IBAction,請幫我解釋一下如何實現它。使用另一個UIViewController的IBAction調用一個UIControllerView的IBAction iOS

假設, 我有兩個UIViewController中名爲FirstViewContoller和SecondViewController,現在我有FirstViewController和另一IBAction爲一個IBAction爲在SecondViewController,現在我想對FirstViewControllers IBAction爲的點擊使用SecondViewControllers IBAction爲。

我該如何執行這種工作。

代碼片段將可觀。

在此先感謝。

+0

你想要做什麼與第二vc的插座的行動?設置一些價值,如果你可以說或清楚,那麼它會有所幫助。 –

+0

其實我必須把我的工作代碼放入第二個vc中,並且我有第一個vc上的按鈕,所以我想在第一個vc中單擊按鈕時使用第二個vc的IBAction。 –

+0

你想在SecondVC上調用方法,或者觸發代碼。如果你需要第一個,它很容易。所有你需要做的是SecondVC()。myMethod(),但如果第二種情況有點不清楚。 – kandelvijaya

回答

0

爲您說明了情況「其實我已經把我的工作代碼在二VC和我對第一個VC按鈕,所以我想用第二VC的IBAction爲當我在第一個VC按鈕點擊。」這是你可以做到這一點。

//this if from FirstVC 
@IBAction func doSomething(sender:UIButton!){ 
let computedThing = SecondViewController().computeThisThing() 
//do what your app needs now 
} 

請記住在SecondViewController上有確切的方法和返回類型。 的SecondViewControllers IBAction爲看起來像這樣

//This is from the Second VC 
@IBAction func doSomethingHere(sender:UIButton!){ 
let computedThing = computeThisThing() 
//do what your app needs now 
} 

func computeThisThing() ->String { //or whatever data type is required 
//do some work 
return "something" 
} 

但我勸你,重構出公共代碼到一個單獨的類,並使用它。這使得體系結構的設計堅實並遵循單一對象單一職責設計模式。

讓我知道這是否有幫助。乾杯!

1

您可以通過在SecondViewController.m的出口操作方法使用委託

在FirstViewController.h

@protocol myDelegate <NSObject> 

-(void)changeValue; 

@end 

@interface FirstViewController : UIViewController 

@property (nonatomic,weak) id <myDelegate>delegate; 

和SecondViewController.h

#import "FirstViewController.h" 

@interface SecondViewController : UIViewController<myDelegate> 

再次做到這一點

-(IBAction)mySecondViewControllerOutlet:(id)sender{ 
    FirstViewController *v = [[FirstViewController alloc]init]; 
    [v.delegate changeValue ]; 
} 

最後在FirstViewController.m

-(void)changeValue{ 
//Write down the change of code you want to implement 
} 

希望這會有所幫助。

相關問題