Search code examples
iosxcodeuibuttontoastunrecognized-selector

Android's "Toast" in iOS: adding button to message


I have created an iOS class for a ToastView (similar to Android's toast) that displays a message bar at the bottom of the screen. I added a button to the ToastView, and solved my original error. The NSLog for touching the button shows up in the console, but I need to send a BOOL value back to HomeViewController when the button is clicked and I'm not sure how to communicate between the two with this button. Any help?

in ToastView.h:

+ (void)showToastInParentView: (UIView *)parentView withText:(NSString *)text withDuaration:(float)duration;
+ (void)undoButtonClicked:(id)sender;

in ToastView.m:

//shows the "toast" message
+ (void)showToastInParentView: (UIView *)parentView withText:(NSString *)text withDuaration:(float)duration {
//code to show message
UIButton *undoButton = [[UIButton alloc] initWithFrame:CGRectMake(toast.frame.size.width - 60.0, toast.frame.size.height - 35.0, 40, 20)];
undoButton.backgroundColor = [UIColor lightGrayColor];
[undoButton addTarget:self action:@selector(undoButtonClicked:) forControlEvents:UIControlEventTouchDown];
}

+(void) undoButtonClicked:(id)sender {
NSLog(@"UNDO BUTTON TOUCHED");
}

and I call ToastView with the following code in my HomeViewController:

[ToastView showToastInParentView:self.view withText:@"TOAST MESSAGE!" withDuaration:5.0];

Solution

  • Seeing your updated code, the problem comes from the undoButtonClicked: method, which in your case is a class method (prefixed with "+").

    You want to make it an object method by changing the prefix with "-". That way, the class knows it's made to be called on an instantiated object of this class. When you use addTarget:action:forControlEvents:, the action is a selector of your target.

    As Apple says:

    A selector is the name used to select a method to execute for an object

    So it needs to be an object method, not a class method.

    Your code should look like that:

    .h:

    + (void)showToastInParentView: (UIView *)parentView withText:(NSString *)text withDuaration:(float)duration;
    - (void)undoButtonClicked:(id)sender;
    

    .m:

    //shows the "toast" message
    + (void)showToastInParentView: (UIView *)parentView withText:(NSString *)text withDuaration:(float)duration {
        //code to show message
        UIButton *undoButton = [[UIButton alloc] initWithFrame:CGRectMake(toast.frame.size.width - 60.0, toast.frame.size.height - 35.0, 40, 20)];
        undoButton.backgroundColor = [UIColor lightGrayColor];
        [undoButton addTarget:self action:@selector(undoButtonClicked:) forControlEvents:UIControlEventTouchDown];
    }
    
    -(void) undoButtonClicked:(id)sender {
        NSLog(@"UNDO BUTTON TOUCHED");
    }