【问题标题】:iOS Subclassed UIView - How to have UIButton call method from ViewController?iOS 子类化 UIView - 如何从 ViewController 调用 UIButton 方法?
【发布时间】:2012-09-13 16:55:57
【问题描述】:

我有一个自定义 UIView 用于显示弹出框(在 iPhone 上)。在弹出窗口中有一些 UIButton,我需要从 ViewController 的类(不是 UIView 的类,而是显示 UIView 的 View)中调用方法。

如何正确设置?

位于自定义 UIView 类中的 UIView 按钮代码:

    UIButton *logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [logoutButton setTitle:@"Logout" forState:UIControlStateNormal];
    [logoutButton setFrame:CGRectMake(0, 0, content.frame.size.width, 44)];
    [logoutButton addTarget:self.superview.superview action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
    [logoutButton setBackgroundImage:redImage forState:UIControlStateNormal];
    [logoutButton setBackgroundImage:redImageHighlight forState:UIControlStateHighlighted];
    [logoutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [content addSubview:logoutButton];

【问题讨论】:

  • 视图不应负责非视图逻辑,例如呈现弹出框。您应该处理按钮的触摸事件和您的视图控制器并从那里呈现弹出窗口。

标签: ios uiview methods uibutton


【解决方案1】:

最好的方法是在你的 UIView 子类中使用委托模式来在你的注销按钮被按下时通知所有者。在视图控制器中创建视图实例时,将委托设置为 self。

http://enroyed.com/ios/delegation-pattern-in-objective-c-and-writing-custom-delegates/中签出“编写自定义委托”

无法以您在上面代码中尝试的方式访问连接到超级视图的 ViewController。

或者,您可以发布通知。例如。发送一条应用程序范围的消息,表明应该执行注销。查看 NSNotificationCenter 了解如何执行此操作。

类似:

[[NSNotificationCenter defaultCenter] postNotificationName:kShouldLogOutNotification object:nil];

编辑:您肯定希望在您的用例中使用委托。

【讨论】:

  • 虽然技术上可行,但通知是解决此问题的错误解决方案。
  • @titaniumdecoy 同意,代表是要走的路。
【解决方案2】:

这类事情通常是通过 delegate 来完成的,这是 UIKit 中大量使用的设计模式。见:What is the purpose of an iOS delegate?

【讨论】:

    【解决方案3】:

    好的,所以我相信创建自定义委托是处理此问题的正确方法。 但是,我确实发现这种方法可以正常工作(但不确定它是否“正确”)

    [logoutButton addTarget:self.superview action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
    

    这似乎告诉按钮使用它的超级视图(UIView)的类(ViewController)。 同样,不确定这是否是从主视图控制器调用方法的正确/正确方法,但它可以正常工作,因此看起来很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 2015-05-19
      相关资源
      最近更新 更多