【问题标题】:Custom UIView linked to UIViewController - how to handle button actions链接到 UIViewController 的自定义 UIView - 如何处理按钮操作
【发布时间】:2016-06-08 21:00:42
【问题描述】:

我对在 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 一无所知...

【问题讨论】:

  • 您是否在为这个自定义视图使用 Xib?

标签: ios objective-c uiview uiviewcontroller


【解决方案1】:

如果您不使用情节提要或 .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”)

【讨论】:

  • 它有效,但它是好方法吗?如果我有这样的问题,是不是我做建筑的方式不对?
  • 这是一个糟糕的架构。您应该将自定义视图添加为子视图并将视图控制器设置为自定义视图的委托,以便它可以调用视图控制器的方法或将其设置为按钮的目标。
猜你喜欢
  • 2019-06-02
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
相关资源
最近更新 更多