ios – 正确访问segue的目标视图控制器以分配协议代理

前端之家收集整理的这篇文章主要介绍了ios – 正确访问segue的目标视图控制器以分配协议代理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在实现选择列表时遇到了集成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];

没有显示警报,因为,我认为,我没有将selectController传递给目标选择列表.有什么想法可以解决这个问题吗?

解决方法

使用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.

猜你在找的iOS相关文章