標籤:class blog code http ext get
NSWindowController 多個視窗之間傳遞值
主介面一個按鈕點擊,出現另一個視窗,然後輸入123,點OK,在主介面的編輯框內可以得到123這個值,
思路:
由於要給主介面的控制項賦值,所以在第二個視窗裡面設定一個同類型的變數。
然後主介面的控制項 = 第二個視窗的同類型變數。
例如:主介面是
NSTextField 控制項1,
那麼就在子視窗裡面設定這樣一個變數(NSTextField a1),給值。
然後在主介面調用時,讓主介面的NSTextField 控制項1 =a1
這樣主介面就可以得到子介面的值了。
子介面代碼如下
H檔案
//// Form1.h// test_multi_window//// Created by EDU on 3/6/14.// Copyright (c) 2014 EDU. All rights reserved.//#import <Cocoa/Cocoa.h>@interface Form1 : NSWindowController@property (assign) IBOutlet NSWindow *window_form1;@property (assign) NSInteger *button_ok_flag;@property (assign) NSString *button_string;@property (assign) IBOutlet NSTextField *m_Edit1;@property (assign) IBOutlet NSTextField *form_main;@property (assign) IBOutlet NSTextField *form_main_m_ET1;@property bool form_ok_cancel_result;-(void)get_value;@end
M檔案
//// Form1.m// test_multi_window//// Created by on 3/6/14.// Copyright (c) 2014 EDU. All rights reserved.//#import "Form1.h"#import "EDUAppDelegate.h"@interface Form1 ()@end@implementation Form1@synthesize form_main;@synthesize form_main_m_ET1;@synthesize window_form1;@synthesize button_ok_flag;@synthesize button_string;@synthesize m_Edit1;@synthesize form_ok_cancel_result;- (id)initWithWindow:(NSWindow *)window{ NSLog (@"init()"); self = [super initWithWindow:window]; if (self) { } return self;}- (void)windowDidLoad{ [super windowDidLoad]; }- (IBAction)OnBT_OK:(id)sender{ form_main.stringValue = @"OK"; form_ok_cancel_result = true; [self get_value]; [super close];}- (IBAction)OnBT_Cancel:(id)sender{ form_main.stringValue = @"CANCEL"; form_ok_cancel_result = false; [self get_value]; [super close];}-(void)get_value{ form_main_m_ET1.stringValue = m_Edit1.stringValue;}@end
主視窗代碼如下
H檔案
//// EDUAppDelegate.h// test_multi_window//// Created by on 3/6/14.// Copyright (c) 2014 EDU. All rights reserved.//#import <Cocoa/Cocoa.h>#import "Form1.h"@interface EDUAppDelegate : NSObject <NSApplicationDelegate>@property (assign) Form1 *m_form1;@property (assign) IBOutlet NSWindow *window;@property (assign) IBOutlet NSTextField *m_label1;@property (assign) IBOutlet NSTextField *m_ET1;@end
M檔案
//// EDUAppDelegate.m// test_multi_window//// Created by EDU on 3/6/14.// Copyright (c) 2014 EDU. All rights reserved.//#import "EDUAppDelegate.h"@implementation EDUAppDelegate@synthesize m_form1;@synthesize m_label1;@synthesize window;@synthesize m_ET1;- (void)dealloc{ [super dealloc];}- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{ // Insert code here to initialize your application}- (IBAction)OnBT_Form1:(id)sender{ if(!m_form1) { m_form1 = [[Form1 alloc] initWithWindowNibName:@"Form1"]; } m_form1.window.title = @"Hello,this is a test"; m_form1.form_main = m_label1; m_form1.form_main_m_ET1=m_ET1; [m_form1 showWindow: sender];}@end
運行編譯OK
完成!