Displaying a message in iOS which has the same functionality as Toast in Android
You can make use of MBProgressHUD
project.
Use HUD mode MBProgressHUDModeText
for toast-like behaviour,
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];// Configure for text only and offset downhud.mode = MBProgressHUDModeText;hud.label.text = @"Some message...";hud.margin = 10.f;hud.yOffset = 150.f;hud.removeFromSuperViewOnHide = YES;[hud hideAnimated:YES afterDelay:3];
NSString *message = @"Some message...";UIAlertView *toast = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];[toast show]; int duration = 1; // duration in seconds dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [toast dismissWithClickedButtonIndex:0 animated:YES];});
Using UIAlertViewController for iOS 9 or later
NSString *message = @"Some message...";UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];[self presentViewController:alert animated:YES completion:nil];int duration = 1; // duration in secondsdispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [alert dismissViewControllerAnimated:YES completion:nil];});
Swift 3.2
let message = "Some message..."let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)self.present(alert, animated: true) // duration in secondslet duration: Double = 5 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) { alert.dismiss(animated: true)}
In Android, a Toast is a short message that displays on the screen for a short amount of time and then disappears automatically without disrupting user interaction with the app.
So a lot of people coming from an Android background want to know what the iOS version of a Toast is. Besides the current question, other similar questions can be found here, here, and here. The answer is that there is no exact equivalent to a Toast in iOS. Various workarounds that have been presented, though, including
- making your own Toast with a
UIView
(see here, here, here, and here) - importing a third party project that mimics a Toast (see here, here, here, and here)
- using a buttonless Alert with a timer (see here)
However, my advice is to stick with the standard UI options that already come with iOS. Don't try to make your app look and behave exactly the same as the Android version. Think about how to repackage it so that it looks and feels like an iOS app. See the following link for some choices.
Consider redesigning the UI in a way that conveys the same information. Or, if the information is very important, then an Alert might be the answer.