2016-06-08 88 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

相关问题