简体   繁体   中英

UIButton Target Action inside UIView

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()
}

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

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.

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()
    }
}

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

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

Thomas: Please correct me if I understood wrongly. I assume you have one ViewController (SomeOtherViewController) and Custom class for UIView (CustomView). Inside custom view, you have a button. You are passing the someotherviewcontroller pointer to customview class and reloading the controller view (Calendar).

If the above scenario is right, then I feel better you create a protocol in CustomView class and implement that protocol method in SomeOtherViewController and reload the data in that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM