Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
41 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...