我正在尝试创建一个提醒,提示用户为他们导入到乐谱显示应用程序中的歌曲命名。
我已经为这个命名过程创建了一个函数:
- (NSString *)nameImportedSong {
NSString *songName;
UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"New Song"
message: @"Choose a song name"
preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"song name";
textField.textColor = [UIColor blueColor];
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.borderStyle = UITextBorderStyleRoundedRect;
}];
[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSArray * textfields = alertController.textFields;
UITextField * namefield = textfields[0];
NSString *chosenSongName = [NSString stringWithFormat:@"%@", namefield.text];
}]];
songName = ; // <-------------how do I assign chosenSongName to songName?
[self presentViewController:alertController animated:YES completion:nil];
return songName;
}
如何在警报之外将警报中的 chosenSongName 分配给我的 songName 变量?
最佳答案
为变量使用__block关键字
__block NSString *chosenSongName;
[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSArray * textfields = alertController.textFields;
UITextField * namefield = textfields[0];
chosenSongName = [NSString stringWithFormat:@"%@", namefield.text];
}]];
songName = chosenSongName;
NSLog(@"chosenSongName = %@",chosenSongName);
关于ios - 访问在 alertController 中声明的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44510275/