UIView 中的 UIButton 目标操作 [英] UIButton Target Action inside UIView

查看:25
本文介绍了UIView 中的 UIButton 目标操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个自定义 UIView,其中有一个 UIButton.在该视图中,我有以下代码:

I have a custom UIView I created in which I have a UIButton. Inside that view, I have this code:

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 调用另一个控制器的函数.

Is this a bad practice to do though? Especially since I'm calling another controller's function through a custom UIView.

我应该把这些方法放在 ViewController 中吗?或者有没有更好的方法来做到这一点?

Should I instead make it so these methods are in the ViewController? Or is there a better way to do this?

推荐答案

我认为在视图内部了解父结构并不是一个好主意.它破坏了封装并导致难以维护、错误和额外的关系.

I thinks it is not a good idea to know inside the view about parent structures. It is breaks encapsulation and leads to hard maintenance, bugs and extra relations.

作为一种简单的方法,您可以为您的自定义 UIView 定义函数 addTarget,它将像一座桥梁一样工作.

As a simple way you can define function addTarget for your custom UIView, that will work like a bridge.

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 一无所知

Then your controller only knows that UICustomView can handle events and UICustomView have know nothing about SomeOtherViewController

如果您的自定义视图中有多个按钮,那么实现类似 UIAlertController 类型为 UIAlertControllerStyle.ActionSheet 的东西可能是个好主意

If you have more than one button inside you custom view perhaps it would be a good idea to implement something like UIAlertController with type UIAlertControllerStyle.ActionSheet

这篇关于UIView 中的 UIButton 目标操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆