简体   繁体   中英

Swift - Dynamically added action doesn't fire

I have a function which should "toggle" a bar button item by changing between 2 images.

class Buttons {
    func ToggleBarButton(button : UIBarButtonItem, name : String, location : BarButtonLocation, isEnabled : Bool, viewController : UIViewController) {
        var iconName = name
        if (!isEnabled) {
            iconName += "EnabledIcon"
        } else {
            iconName += "DisabledIcon"
        }

        let newIcon = UIImage(named: iconName)
        let newButton = UIBarButtonItem(image: newIcon, style: .Plain, target: self, action: button.action);

        switch location {
        case BarButtonLocation.Left:
            viewController.navigationItem.leftBarButtonItem = newButton;
            viewController.navigationItem.leftBarButtonItem?.tintColor = UIColor.blackColor();
        case BarButtonLocation.SecondLeft:
            viewController.navigationItem.leftBarButtonItems?[1] = newButton
            viewController.navigationItem.leftBarButtonItems?[1].tintColor = UIColor.blackColor()
        default:
            return;
        }
    }
}

I also have a view controller class, in which there is the action of the bar button item.

class GradesViewController: UIViewController {
    var isFilterEnabled = false
    var isViewEnabled = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func filterButton_Pressed(sender: UIBarButtonItem) {
        Buttons().ToggleBarButton(sender, name : "Filter", location: BarButtonLocation.Left, isEnabled: isFilterEnabled, viewController: self);
        isFilterEnabled = !isFilterEnabled;
    }

    @IBAction func viewButton_Pressed(sender: UIBarButtonItem) {
        Buttons().ToggleBarButton(sender, name : "View", location: BarButtonLocation.SecondLeft, isEnabled: isViewEnabled, viewController: self);
        isViewEnabled = !isViewEnabled;
    }
}

On first press it successfully changes the image to the enabled form, but on second press it doesn't do anything (press event doesn't even fire). I checked, and button.action is correctly identified as "filterButton_Pressed:" . What's the problem, or is there an easier way to do this? Thanks for the answer in advance.

Put the break statement after each case and try. And also remove the semi colons.

I just realized the problem was that I copied the code from the view controller to the button class, and didn't change target: self to target: viewController . But thanks for all the answers anyways...

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