使用UISegmentedControl在视图之间传递值

时间:2012-12-15 00:46:24

标签: iphone ios mkmapview uisegmentedcontrol

我正在尝试在两个视图之间传递一个整数。当我从View1返回到MainView时,该值未传递,NSLog(@“更改的地图”)未显示在控制台中。我寻找答案并尝试了一切,但它不起作用!感觉像代表那样的错误......

有什么想法吗?

View1.h

@class FlipsideViewController;

@protocol FlipsideViewControllerDelegate
    - (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller;
    -(void)flipsideViewControllerSelectionChangedToIndex:(int)index;
    @end

@interface FlipsideViewController : UIViewController {
}

@property (weak, nonatomic) id <FlipsideViewControllerDelegate> delegate;
@property (nonatomic, retain) IBOutlet UISegmentedControl *mapType;

- (IBAction)valueChangedMap:(id)sender;

@end

View1.m

-(IBAction)valueChangedMap:(id)sender {
    [self.delegate flipsideViewControllerSelectionChangedToIndex:[sender selectedSegmentIndex]];
    NSLog (@"%d",[sender selectedSegmentIndex]);

    [self dismissViewControllerAnimated:YES completion:nil];
}

MainView.h

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate, UIPopoverControllerDelegate, MKMapViewDelegate> {}

@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property(weak) id<FlipsideViewControllerDelegate> delegate;

@end

MainView.m

-(void)flipsideViewControllerSelectionChangedToIndex:(int)index {
    NSLog(@"Changed map");

    if (index == 0) mapView.mapType = MKMapTypeStandard;
    if (index == 1) mapView.mapType = MKMapTypeHybrid;
    if (index == 2) mapView.mapType = MKMapTypeSatellite;
}

1 个答案:

答案 0 :(得分:0)

您只需要view1上的实际委托属性,而您的mainView只需要响应该委托协议。以下是您的委托协议应该是什么样的:

@property(nonatomic,unsafe_unretained) id delegate;

现在在代码中,当mainview显示或推送view1时,你需要像这样连接委托(伪代码):

view1.delegate = self;

还有一些挑剔...你永远不应该让viewcontroller解雇自己,当'完成'委托方法触发时,mainView应该忽略view1。此外,您应始终检查委托在触发前响应选择器:

if([self.delegate respondsToSelector:@selector(yourselectorname)]) {
    [self.delegate yourselectorname];
}