IOS父ViewController获取子ViewCONtroller数据后丢失原始坐标

标签 ios objective-c google-maps-markers protocols

我已经实现了将 subview Controller (SliderViewController)的值传递给主视图 Controller (MapViewController)的模块,但是在实现时,刚刚添加的位置丢失了,因此无法添加坐标数组,因此无法显示?除了将坐标保存到文本文件中并重新加载外,还有其他方法可以保存坐标数组吗?

下面是我的工作:

ChildViewCONtroller

SliderViewController.h

#import <UIKit/UIKit.h>
#import "EFCircularSlider.h"



@protocol SliderViewControllerDelegate <NSObject>
- (void)passData:(float )itemVertical : (float )itemCircular  ;
@end


@interface SliderViewController : UIViewController

@property (strong, nonatomic) IBOutlet UILabel *uiValue;
@property (strong, nonatomic) IBOutlet UISlider *uiSlider;
@property (strong, nonatomic) IBOutlet UIButton *btnReset;
@property (strong, nonatomic) IBOutlet UILabel *uiValue2;
@property (strong, nonatomic)  EFCircularSlider* circularSlider;
@property (nonatomic) float verticalSliderValue;
@property (nonatomic) float circleSliderValue;
@property (nonatomic) id <SliderViewControllerDelegate> delegate;


- (IBAction)reset:(id)sender;
- (IBAction)sliderChange:(id)sender;
- (void)buttonClicked: (id)sender;


@end

SliderViewController.m

#import "SliderViewController.h"
#import <AudioToolbox/AudioServices.h>
#import "MapViewController.h"

@interface SliderViewController (){
    NSString *valueV;
    NSString *valueC;
}

@end

@implementation SliderViewController



- (void)viewDidLoad
{
    [super viewDidLoad];

    _uiSlider.minimumValue = 0.0;
    _uiSlider.maximumValue = 100.0;
    [_uiSlider removeConstraints:_uiSlider.constraints];
    [_uiSlider setTranslatesAutoresizingMaskIntoConstraints:YES];

    float value  = M_PI * -0.5 ;
   _uiSlider.transform = CGAffineTransformMakeRotation(value);

    CGRect sliderFrame = CGRectMake(60, 300, 100, 100);
   _circularSlider = [[EFCircularSlider alloc] initWithFrame:sliderFrame];
    [_circularSlider addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_circularSlider];
    [_circularSlider setCurrentValue:10.0f];
    [_uiSlider setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.5]];

    CGRect screen = [[UIScreen mainScreen] bounds];
    CGFloat width = CGRectGetWidth(screen);
    CGFloat height = CGRectGetHeight(screen);
    float scale = [[UIScreen mainScreen] scale];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake( 0, 450 ,width/2, 20);
    [button setTitle:@"OK" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16.0];
    button.titleLabel.adjustsFontSizeToFitWidth = TRUE;
    [button setBackgroundColor:[UIColor orangeColor]];

    [button addTarget: self
               action: @selector(buttonClicked:)
     forControlEvents: UIControlEventTouchDown];


    [self.view addSubview:button];
}


- (void) buttonClicked: (id)sender
{
    NSLog( @"Button clicked." );
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)valueChanged:(EFCircularSlider*)slider {
    self.uiValue2.text = [NSString stringWithFormat:@"%.02f", slider.currentValue ];
    _circleSliderValue = slider.currentValue;
    valueC =  self.uiValue2.text;
    if(slider.currentValue  > 20.0 && slider.currentValue  < 30.0  ){
        AudioServicesPlaySystemSound(1003);
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
}

- (IBAction)reset:(id)sender {
    [self writeToTextFile:valueV :valueC];
    MapViewController * sliderVC = [self.storyboard instantiateViewControllerWithIdentifier:@"MapViewController"];
    sliderVC.verticalSliderValue = _uiSlider.value;
    sliderVC.circleSliderValue =_circularSlider.currentValue;
    [sliderVC passData:_uiSlider.value :_circularSlider.currentValue  ];
    sliderVC.modalPresentationStyle = UIModalPresentationCurrentContext;
    [self dismissViewControllerAnimated:YES completion:nil];
  }

-(void) writeToTextFile:(NSString*) values : (NSString*) values2 {
    NSArray *paths = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName = [NSString stringWithFormat:@"%@/slider.txt",documentsDirectory];
    NSString *content = [NSString stringWithFormat:@"%@%@%@%@", values , @"\n" , values2 , @"\n" ];
    [content writeToFile:fileName
              atomically:YES
                encoding:NSStringEncodingConversionAllowLossy
                   error:nil];
      NSLog(@"%@",documentsDirectory);
    [self displayContent];
}

-(void) displayContent{
    NSArray *paths = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName = [NSString stringWithFormat:@"%@/slider.txt",
                          documentsDirectory];
    NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                    usedEncoding:nil
                                                           error:nil];
    NSLog(@"%@",content);
}


- (IBAction)sliderChange:(id)sender {
    UISlider *slider = (UISlider *)sender;
    NSString *newValue = [NSString stringWithFormat:@"%.2f" , slider.value];
    _verticalSliderValue = slider.value;
    self.uiValue.text = newValue;
    valueV  = self.uiValue.text;
    if(slider.value > 30 && slider.value < 50){
        AudioServicesPlaySystemSound(1003);
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

MasterViewController

MapViewController.h

    #import <MessageUI/MessageUI.h>
    #import <GoogleMaps/GoogleMaps.h>
    #import <UIKit/UIKit.h>
    #import "SliderViewController.h"


    @interface MapViewController : UIViewController<GMSMapViewDelegate , SliderViewControllerDelegate>{


    }

    @property (nonatomic) float verticalSliderValue;
    @property (nonatomic) float circleSliderValue;


    @end

MapViewCntroller.m



#import "MapViewController.h"
#import "CheckPoints.h"
#import "NSURLRequestSSL.h"
#import "ToastView.h"


@interface MapViewController () {
    GMSMapView *mapView_;
    NSMutableArray *array;
    GMSCameraPosition *camera;
    NSArray *_styles;
    NSArray *_lengths;
    NSArray *_polys;
    double _pos, _step;
    CLLocationCoordinate2D p;
}


@end

@implementation MapViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self getTime];
    array = [[NSMutableArray alloc] init];
    // Create a GMSCameraPosition that tells the map to display the
    // coordinate -33.86,151.20 at zoom level 6.uisplatch

    camera = [GMSCameraPosition cameraWithLatitude:22.2855200
                                                            longitude:114.1576900
                                                                 zoom:12];
    mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    mapView_.delegate = self;

    mapView_.myLocationEnabled = YES;
    mapView_.settings.compassButton = YES;
    mapView_.settings.myLocationButton = YES;
    // mapView_.delegate = self;
    self.view = mapView_;

    // Creates a marker in the center of the map.
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(22.2855200, 114.1576900);
    marker.title = @"My place";


    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    // defaults
    float latitide = [defaults floatForKey:@"lati"];
    float longitude = [defaults floatForKey:@"longi"];
    NSString *desp = [defaults objectForKey:@"desp"];

    if(latitide!=0.00&&longitude!=0.00) {
        CLLocationCoordinate2D position = CLLocationCoordinate2DMake(latitide, longitude);
        marker.position = CLLocationCoordinate2DMake(position.latitude, position.longitude);
    }
    if(desp.length > 0 ){
        marker.title = desp;
    }

    marker.snippet = @"HK";
    marker.map = mapView_;

}


...


    - (void)passData:(float )value1 : (float )valueCiruclar
{
 NSLog(@"This was returned from ViewControllerB %ff",value1);
    NSLog(@"This was returned from ViewControllerSlider %ff",valueCiruclar);


    [mapView_ clear];

    NSLog(@"This was map received");

    CheckPoints *myCar=[[CheckPoints alloc] init];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    float latitide = [defaults floatForKey:@"lati"];
    float longitude = [defaults floatForKey:@"longi"];
    NSString *desp = [defaults objectForKey:@"desp"];



    [myCar setLatitude:latitide];
    [myCar setLongitude:longitude];
    [myCar setDesp:desp];
    [myCar setState:[desp length] > 0 ? 0 : 1];



    [CarArray addObject:myCar];


    NSLog(@"This was returned lat from ViewControllerB %ff",[myCar getLatitude]);
    NSLog(@"This was returned longi from ViewControllerSlider %ff",[myCar getLongitude]);
    NSLog(@"This was returned desp from ViewControllerB %@",[myCar getDesp]);
    NSLog(@"This was returned state from ViewControllerSlider %i",[myCar getState]);

    lastChk = CarArray.lastObject;
    [self writeToTextFile:[NSString stringWithFormat:@"%@%@%@%@%@%@", lastChk.getDesp , @"\n",[NSString stringWithFormat:@"%f", lastChk.getLatitude],
                           @"\n", [NSString stringWithFormat:@"%f", lastChk.getLongitude], @"\n" ]];

    NSLog(@"This was map arraoy count @%i" , [CarArray count]);

    for (int i = 0; i < [CarArray count]; i++) {
        CheckPoints *current =  [CarArray objectAtIndex:i];
        if(current.getLatitude != lastChk.getLatitude && current.getLongitude != lastChk.getLongitude){
            [current setState:1];
            NSString* previousTitle = [NSString stringWithFormat:@"%@%@", @"Checkpoint" ,[NSString stringWithFormat:@"%i", i+1]];
            [current setDesp:previousTitle];
        }
    }
    [self addMarkers];








    -(void) mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate{

        p = coordinate;
        SliderViewController * sliderVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SliderViewController"];
        sliderVC.view.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0];
        sliderVC.modalPresentationStyle = UIModalPresentationCurrentContext;
        [self presentViewController:sliderVC animated:YES completion:NULL];

    }

最佳答案

-(void) mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate
{
    p = coordinate;
    SliderViewController * sliderVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SliderViewController"];
    sliderVC.view.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0];
    sliderVC.modalPresentationStyle = UIModalPresentationCurrentContext;
    **[sliderVC setDelegate:self]**
    [self presentViewController:sliderVC animated:YES completion:NULL];
}

- (IBAction)reset:(id)sender 
{
    [self writeToTextFile:valueV :valueC];
    [self.delegate passData:_uiSlider.value :_circularSlider.currentValue  ];
    [self dismissViewControllerAnimated:YES completion:nil];
}

不要创建新实例。您只需要使用委托(delegate)即可。

关于IOS父ViewController获取子ViewCONtroller数据后丢失原始坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24526307/

相关文章:

ios - 在 Xcode 中滚动时固定导航栏

ios - 如何在应用程序委托(delegate)上的服务器调用后更改根 Controller ?

objective-c - 窗口大小改变时的 NSWindow 事件

ios - MSMessage url 在将其设置为文件的 url 后保持为 nil

iphone - 在项目中使用 ShareKit 时,本地化字符串并不总是有效

ios - 为什么在 iOS 中调用 UIImageJPEGRepresentation 会改变图像的数据

iphone - 当触摸移动时找到我们触摸下的物体

android - 如何在 Google Map API v2 中的 MapFragment 上显示多个标记?

javascript - 单击标记时获取地址 - Google map

android - 如何使标记根据缩放级别 Google Maps v2 调整其大小