【问题标题】:How can I specify a target for my action to point to?如何为我的操作指定一个目标?
【发布时间】:2014-07-01 03:55:04
【问题描述】:

我正在学习 iOS 的 Objective-c,并且有一个关于创建我的第一个目标动作机制的问题。我已经让它工作了,但目前我只是将addTarget:action:changeForControlEvents: 方法的target: 部分设置为nil,这意味着它将在我的应用程序中搜索目标,而不是向下钻取ViewController.m,其中我要发送消息的方法位于。

如何告诉addTarget:action:changeForControlEvents: 方法首先搜索哪个类?

这是我当前代码的简单版本:

观点:

// View.m
#import View.h

@implementation

- (void)sendAction
{
     UIControl *button = [[UIControl alloc] init];
     [button addTarget:nil  // How do I make this look for ViewController.m?
                action:@selector(changeButtonColor) 
changeforControlEvents:UIControlEventTouchUpInside];
}
@end

...和视图控制器:

// ViewController.m
#import ViewController.h

@implementation

- (void)target
{
     NSLog(@"Action received!");
}
@end

感谢您的帮助!

【问题讨论】:

  • 一种常见的方法是委托模式,它被广泛覆盖。有一篇很好的基本文章 here 或查看有关此主题的许多现存的 Stack Overflow 问题。
  • @rfarry 在这里你可以使用委托方法...
  • 您可以通过提及目标作为对ViewController 类的引用来指向ViewController.m 中的changeButtonColor

标签: ios objective-c xcode uicontrol target-action


【解决方案1】:

如果UIViewController 没有在内存中加载或分配,则不能简单地调用它。为此,您需要分配该类。

使用singleton的一种方法

[button addTarget:[ViewController sharedManager] action:@selector(target) 
forControlEvents:UIControlEventTouchUpInside];

或使用NSNotificationCenter,假设该类已经在运行(堆栈在以前的导航/另一个选项卡中)。

// View.m
#import View.h
@implementation

- (void)sendAction
{
     UIControl *button = [[UIControl alloc] init];
     [button addTarget:self 
                action:@selector(controlAction) 
changeforControlEvents:UIControlEventTouchUpInside];
}

-(void)controlAction
{
 [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"changeButtonColor" 
        object:self];
}
@end

对于目标UIViewController

// ViewController.m
#import ViewController.h

@implementation
-(void) viewDidLoad
{
   [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(receiveNotification:) 
        name:@"changeButtonColor"
        object:nil];

- (void)receiveNotification:(NSNotification *) notification

{
     NSLog(@"Action received!");
}
@end

【讨论】:

  • 我还没有处理通知,但是大多数设计模式不是都规定它们只是为了让模型向视图控制器和可能的视图广播信息吗?不过谢谢,非常有帮助。
【解决方案2】:

假设 ViewController 是创建您正在使用的视图的 VC,您应该能够使用:

addTarget:[自己的超级视图]

【讨论】:

  • 谢谢,这也有效,但这几乎正是我的代码隐式所做的(除了它不在当前实例中搜索)。我正在寻找一种在特定实例中开始搜索的方法。
猜你喜欢
  • 1970-01-01
  • 2013-02-01
  • 1970-01-01
  • 2011-04-01
  • 2012-02-28
  • 2013-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多