我在实现选择列表时遇到了集成segue和协议的一些问题.
在我的选择列表中.h我有:
#import <UIKit/UIKit.h> @protocol SelectionListViewControllerDelegate <NSObject> @required - (void)rowChosen:(NSInteger)row; @end @interface SelectColor : UITableViewController <NSFetchedResultsControllerDelegate> -(IBAction)saveSelectedColor; @property (nonatomic,strong) id <SelectionListViewControllerDelegate> delegate; @end
在我的选择列表中.我有:
@implementation SelectColori @synthesize delegate; //this method is called from a button on ui -(IBAction)saveSelectedColore { [self.delegate rowChosen:[lastIndexPath row]]; [self.navigationController popViewControllerAnimated:YES]; }
我想通过从另一个表视图执行segue来访问此选择列表视图:
@implementation TableList ... - (void)selectNewColor { SelectColor *selectController = [[SelectColor alloc] init]; selectController.delegate = (id)self; [self.navigationController pushViewController:selectController animated:YES]; //execute segue programmatically //[self performSegueWithIdentifier: @"SelectColorSegue" sender: self]; } - (void)rowChosen:(NSInteger)row { UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error Title" message:@"Error Text" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [errorAlert show]; }
如果我使用以下方法导航到选择列表:
[self.navigationController pushViewController:selectController animated:YES];
显示警报.如果我改为使用:
[self performSegueWithIdentifier: @”SelectColorSegue” sender: self];
解决方法
使用Segue将数据传递给destinationViewController时,您需要使用该方法
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"SelectColorSegue"]) { SelectColor *vc = segue.destinationViewController; vc.delegate = self; } }
来自Apple Docs
The default implementation of this method does nothing. Subclasses can override it and use it to pass any relevant data to the view controller that is about to be displayed. The segue object contains pointers to both view controllers among other information.