2017-06-12 110 views
0

我試圖創建一條提示,提示用戶命名他們已導入到音樂表顯示應用的歌曲。訪問alertController中聲明的變量

我創建了一個功能,這個命名過程:

- (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變量,警報之外?

回答

2

使用__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); 
+0

完美的作品。謝謝。 – Lorraine