UIView内的UIButton Target Action

我有一个自定义的UIView我在其中创build了一个UIButton 。 在这个视图里面,我有这样的代码:

 func setupViews() { menuControlButton.addTarget(self, action: "toggleButton:", forControlEvents: .TouchUpInside) } func toggleButton(sender: MenuControlButton!) { let isActive = sender.toggleActive() // switches button image and returns whether active or not after NSUserDefaults.standardUserDefaults().setBool(isActive, forKey: sender.title) someOtherViewController.reloadCalendar() } 

这是一个不好的做法吗? 特别是因为我通过自定义UIView调用另一个控制器的function。

我应该这样做,所以这些方法在ViewController? 还是有更好的方法来做到这一点?

我认为在关于父母结构的观点内部不是一个好主意。 这是破解封装,导致难以维护,错误和额外的关系。

作为一个简单的方法,你可以定义函数addTarget为自定义的UIView,这将像桥梁一样工作。

 class UICustomView { func addTarget(target: AnyObject, action: Selector, forControlEvents: UIControlEvents) { menuControlButton.addTarget(target, action: action, forControlEvents: forControlEvents) } func setupViews() {...} func toggleButton(sender: MenuControlButton!) {...} class SomeOtherViewController { func someInitFunc { let viewWithButton = UICustomView() viewWithButton.addTarget(self, "foo:", .TouchUpInside) } func foo(sender: AnyObject) { let isActive = sender.toggleActive() // switches button image and returns whether active or not after NSUserDefaults.standardUserDefaults().setBool(isActive, forKey: sender.title) self.reloadCalendar() } } 

那么你的控制器只知道UICustomView可以处理事件,而UICustomView对SomeOtherViewController一无所知

如果您在自定义视图中有多个button,那么实现类似于UIAlertControllerStyle.ActionSheet的UIAlertController是个好主意

托马斯:如果我理解错了,请纠正我。 我假设你有一个ViewController(SomeOtherViewController)和UIView(CustomView)的自定义类。 在自定义视图里面,你有一个button。 您将someotherviewcontroller指针传递给customview类并重新加载控制器视图(日历)。

如果上面的情况是正确的,那么我觉得在CustomView类中创build一个协议,并在SomeOtherViewController中实现该协议方法,并重新加载数据。