2016-06-08 87 views
0

我很困惑與UIViewController和UIView之間分裂組件。比方說,我做了自定義的UIView與子視圖:自定義UIView鏈接到UIViewController - 如何處理按鈕動作

@interface CustomView : UIView 

@property(strong, nonatomic) UITextField *textField; 
@property(strong, nonatomic) UIButton *button; 
@property(strong, nonatomic) UIImageView *image; 

@end 

我想什麼是從視圖推按鈕我是從文本框取價值,推動新navigationController後實現控制器。但我不知道如何正確地做到這一點。我現在正在嘗試的是這樣的:

@implementation CustomViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    CustomView *customView = [[CustomView alloc] init]; 
    [customView.searchButton addTarget:self action:@selector(didPushSearchButton) forControlEvents:UIControlEventTouchUpInside]; 
    self.view = customView; 
} 

- (void)didPushSearchButton { 
    //pushing new viewController, but how can i get value from text field here? 
} 

@end 

我可以說CustomViewController,它的視圖是類型CustomView?我可以獲得textField的值,因爲我可以輸入self.view.textField。現在打字self.view之後 - 如果你不使用故事板或文件的.xib視圖控制器不知道什麼文本框...

+0

您是否在這個自定義視圖中使用Xib? – Jaimish

+0

不,全部用代碼 – magiczek91

回答

0

,那就試試這個:

// CustomViewController.h 
@interface CustomViewController : UIViewController 

@property (strong, nonatomic) CustomView *view; 

@end 

// CustomViewController.m 
@implementation CustomViewController 

@dynamic view; 

- (void)loadView { 
    CustomView *customView = [[CustomView alloc] initWithFrame:UIScreen.mainScreen.applicationFrame]; 
    [customView.searchButton addTarget:self action:@selector(didPushSearchButton) forControlEvents:UIControlEventTouchUpInside]; 
    self.view = customView; 
} 

@end 

(改「Overriding uiviewcontroller's view property, done right」)

+0

它的作品,但它是好辦法?如果我有這樣的問題,這是否意味着我以錯誤的方式製造建築? – magiczek91

+0

這是糟糕的體系結構。您應該將自定義視圖添加爲子視圖,並將視圖控制器設置爲自定義視圖的委託,以便它可以調用視圖控制器的方法或將其設置爲按鈕的目標。 – Armin

相關問題