【问题标题】:Passing action to one uiview to another in IOS在IOS中将动作传递给一个uiview到另一个
【发布时间】:2012-11-19 19:53:09
【问题描述】:
我创建了一个名为ImageShowcase 的UIView,它有一个UIScrollView,然后我添加了UIButton 继承的类调用ImageShowcaseCell。它工作正常。我感到困惑的一件事是在视图控制器中处理动作的最佳方法是什么,我已经添加了ImageShowCase,目前我可以在UIButton 继承类ImageShowcaseCell 中处理UIControlEventTouchUpInside 动作,但我想处理它在View Controller 中,以便我可以执行适当的操作。
实现这一目标的最佳方法是什么。
【问题讨论】:
标签:
ios
uiview
uibutton
uicontrolevents
【解决方案1】:
在您的自定义 ImageShowcaseCell 类中,您可以将动作发送到响应者链并允许视图控制器处理它:
[[UIApplication sharedApplication] sendAction:@selector(someMethodOnMyViewController:) to:nil from:self forEvent:nil];
或者你也可以使用:
- 委托模式 - 将您的视图控制器设置为 ImageShowcaseCell 的委托。
- 在您的自定义类中创建一个基于块的方法,以便在触摸后执行该块。
【解决方案2】:
有点晚了,但为什么不使用响应链并在您的ImageShowCaseCell 按钮上添加操作?如果你像这样添加它:
[imageShowCaseCellInstance setTarget:nil action:@selector(methodYouWantCalledOnYourViewController) forControlEvents:UIControlEventTouchUpInside
只要你的imageShowCaseCellInstance 没有实现这个方法而你的视图控制器实现了,响应者链应该把它向上传递(因为nil 是为target 指定的)到你的视图控制器,只要@ 987654327@ 在您的视图控制器的层次结构中。
Edwin 的回答 (https://stackoverflow.com/a/13461504/482557) 有效,但通过在按钮上设置目标可以更明确。
【解决方案3】:
通过使用委托来实现它。我的view controller 中已经有一位代表ImageShowCase。所以我做了什么,我在ImageShowcase 中为ImageShowcaseCell 添加了另一个。现在我将 UIControlEventTouchUpInside 事件从 ImageShowcaseCell 传递给 ImageShowcase,并将 ImageShowcase 传递给 view Controller。
ImageShowcaseCell (TouchUpInside) ----> ImageShowcase ----> ViewController
再干净不过了。 :)