Добавление простого UIAlertView
Какой начальный код я мог бы использовать для создания простого UIAlertView с одной кнопкой "ОК"?
10 ответов
Когда вы хотите, чтобы показывалось предупреждение, сделайте это:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ROFL"
message:@"Dee dee doo doo."
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
// If you're not using ARC, you will need to release the alert view.
// [alert release];
Если вы хотите что-то сделать при нажатии кнопки, реализуйте этот метод делегата:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
// the user clicked OK
if (buttonIndex == 0) {
// do something here...
}
}
И убедитесь, что ваш делегат соответствует UIAlertViewDelegate
протокол:
@interface YourViewController : UIViewController <UIAlertViewDelegate>
Другие ответы уже предоставляют информацию для iOS 7 и старше, однако UIAlertView
устарела в iOS 8.
В iOS 8+ вы должны использовать UIAlertController
, Это замена для обоих UIAlertView
а также UIActionSheet
, Документация: Ссылка на класс UIAlertController. И хорошая статья о NSHipster.
Для создания простого представления предупреждений вы можете сделать следующее:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title"
message:@"Message"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
Свифт 3 / 4:
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
//We add buttons to the alert controller by creating UIAlertActions:
let actionOk = UIAlertAction(title: "OK",
style: .default,
handler: nil) //You can use a block here to handle a press on this button
alertController.addAction(actionOk)
self.present(alertController, animated: true, completion: nil)
Обратите внимание, что, поскольку он был добавлен в iOS 8, этот код не будет работать на iOS 7 и старше. Так что, к сожалению, сейчас мы должны использовать проверку версий следующим образом:
NSString *alertTitle = @"Title";
NSString *alertMessage = @"Message";
NSString *alertOkButtonText = @"Ok";
if ([UIAlertController class] == nil) { //[UIAlertController class] returns nil on iOS 7 and older. You can use whatever method you want to check that the system version is iOS 8+
// Starting with Xcode 9, you can also use
// if (@available(iOS 8, *)) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:alertOkButtonText, nil];
[alertView show];
}
else {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
message:alertMessage
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:alertOkButtonText
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
Свифт 3 / 4:
let alertTitle = "Title"
let alertMessage = "Message"
let alertOkButtonText = "Ok"
if #available(iOS 8, *) {
let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
//We add buttons to the alert controller by creating UIAlertActions:
let actionOk = UIAlertAction(title: alertOkButtonText,
style: .default,
handler: nil) //You can use a block here to handle a press on this button
alertController.addAction(actionOk)
}
else {
let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: alertOkButtonText)
alertView.show()
}
UPD: обновлено для Swift 3/4.
UPD 2: добавлена заметка для @available в Objc-C, начиная с Xcode 9.
UIAlertView устарела на iOS 8. Поэтому, чтобы создать предупреждение на iOS 8 и выше, рекомендуется использовать UIAlertController:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title" message:@"Alert Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
// Enter code here
}];
[alert addAction:defaultAction];
// Present action where needed
[self presentViewController:alert animated:YES completion:nil];
Вот как я это реализовал.
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:@"Title"
message:@"Message"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Ok",nil];
[myAlert show];
В дополнение к двум предыдущим ответам (от пользователя "sudo rm -rf" и "Evan Mulawski"), если вы не хотите ничего делать, когда вы щелкаете мышью по вашему виду оповещения, вы можете просто выделить, показать и выпустить его. Вам не нужно объявлять протокол делегата.
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Title"
message:@"Message"
delegate:nil //or self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert autorelease];
Вот полный метод, который имеет только одну кнопку "ОК", чтобы закрыть UIAlert:
- (void) myAlert: (NSString*)errorMessage
{
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:errorMessage
message:@""
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"ok", nil];
myAlert.cancelButtonIndex = -1;
[myAlert setTag:1000];
[myAlert show];
}
На этой странице показано, как добавить UIAlertController, если вы используете Swift.
Простое предупреждение с массивом данных:
NSString *name = [[YourArray objectAtIndex:indexPath.row ]valueForKey:@"Name"];
NSString *msg = [[YourArray objectAtIndex:indexPath.row ]valueForKey:@"message"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:name
message:msg
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
Для Swift 3:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)