I have a table view with a list of strings as fol开发者_运维技巧lows:
String1
String2
String3
String4
I want to make one of these the default, i.e., when the user taps "String3", an alert view should pop up asking if they want to make that item the default.
How would I implement this alert view in my table view controller?
First you'll want to define an instance variable to keep track of the string that's currently selected. Something like this in your header file will be fine.
NSString *selectedString;
Next, in your tableView:didSelectRowAtIndexPath: delegate method create an alert view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
selectedString = [stringArray objectAtIndex:indexPath.row];
NSString *title = [NSString stringWithFormat:@"Make %@ default?", selectedString];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:@"" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
[alert show];
[alert release];
}
To save the value after the user taps a button in the alert you should use the UIAlertView delegate.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 2)
{
//Do something with selectedString here
}
}
I don't have enough reputation to comment here. But your if statement should be:
if (buttonIndex == 1)
{
//Do something with selectedString here
}
That is to say if you want to do something when the yes button is clicked. Anyways, thanks for the quick tutorial, and apart from that slight typo it worked perfectly.
精彩评论