IOS Delegation with custom class objects; pass object from modal view to parent view

StackOverflow https://stackoverflow.com/questions/22121488

  •  18-10-2022
  •  | 
  •  

문제

First, I apologize for asking another delegation question. I've read many and can't find any that deal with passing something complex...

Here's what I am doing... In my app, I have a ViewController: CollisionViewController where I want to let the user select two vehicles that are involved in a collision. All the vehicles are stored using CoreData and presented modally in SelectVehicleViewController. SelectVehicleViewController lists all the vehicles using a UICollectionView. In CollisionViewController, I have properties for Vehicle1 and Vehicle2 which are of a custom class that describes the properties of a vehicle.

In the CollisionViewController, I am using a UIButton to let the user first select Vehicle1, then Vehicle2 from SelectVehicleViewController presented modally.

I am using seques to determine which button was pressed before presenting the modal SelectVehicleViewController.

How do I setup a protocol that allows the user to pass the selected vehicle from the modal view to the correct vehicle object in the CollisionViewController?

도움이 되었습니까?

해결책

collisionViewController should conform your protocol.

collisionViewController.h

#import "SelectVehicleViewController.h"
@interface ContactViewController : UIViewController <SelectVehicleDelegate>

collisionViewController.m

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqual:@"segueName"]) {
        SelectVehicleViewController* VC = segue.destinationViewController;
        VC.delegate = self;
        //here you should probably send if you will select the vehicule 1 or 2
    }
}

- (void)ViewController:(UIViewController *)sender
         didUpdateData:(NSString *)value {
    //do what you need with new data
    //here you should have info if it is for vehicle 1 or 2
}

SelectVehicleViewController.h

@protocol SelectVehicleDelegate;

@interface SelectVehicleViewController : UIViewController

@property (nonatomic, assign) id <SelectVehicleDelegate> delegate;

@end

@protocol SelectVehicleDelegate <NSObject>

- (void)ViewController:(UIViewController *)sender
             didUpdateData:(NSString *)value;      //adapte according to what you should send back

@end

SelectVehicleViewController.m

//somewhere in a button click or....
[self.delegate ViewController:self didUpdateData:@"new value"];
  //in this function you should have info if it is for vehicle 1 or 2
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top