自定义UIView链接到UIViewController - 如何处理按钮操作

时间:2016-06-08 21:00:43

标签: ios objective-c uiview uiviewcontroller

我对在UIViewController和UIView之间拆分组件感到困惑。假设我使用子视图制作了自定义UIView:

@interface CustomView : UIView

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

@end

我想在控制器中实现的是从视图中按下按钮后我从textField获取值并推送新的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后 - ViewController对textField ...

一无所知

1 个答案:

答案 0 :(得分:0)

如果您没有使用情节提要或.xib文件,请尝试以下操作:

// 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")