微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/iOS/332475.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐