我正在尝试在两个Viewcontrollers之间使用委托,但不幸的是我的代表没有被解雇。我希望有人可以帮我解决问题。我有一个名为MapBackgroundViewController的ViewContoller和一个名为MapsViewController的ViewContoller。如果MapsBackgroundViewController的SegmentedControl发生更改,则应通知MapsViewController。 (我实际上尝试在iPhone上实现类似地图应用程序的东西卷曲)
以下是我的代码的一部分:
MapBackgroundViewController.h
@protocol ChangeMapTyp <NSObject>
@required
- (void)segmentedControllChangedMapType:(MKMapType) type ;
@end
@interface MapBackgroundViewController : UIViewController{
IBOutlet UISegmentedControl *segmentedControl;
MKMapType mapType;
id < ChangeMapTyp> delegate;
}
@property IBOutlet UISegmentedControl *segmentedControl;
@property MKMapType mapType;
@property(strong)id delegate;
- (IBAction)segmentedControllChanged:(id)sender;
MapBackgroundViewController.m
@interface MapBackgroundViewController ()
@end
@implementation MapBackgroundViewController
@synthesize segmentedControl, mapType, delegate;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self setDelegate:self];
NSLog(@"%@",self.delegate);
}
- (IBAction)segmentedControllChanged:(id)sender {
if (segmentedControl.selectedSegmentIndex == 0) {
mapType = MKMapTypeStandard;
}else if (segmentedControl.selectedSegmentIndex == 1) {
mapType = MKMapTypeSatellite;
} else if (segmentedControl.selectedSegmentIndex == 2) {
// [self.delegate setMapType:MKMapTypeHybrid];
mapType = MKMapTypeHybrid;
}
//Is anyone listening
NSLog(@"%@",self.delegate);
if([self.delegate respondsToSelector:@selector(segmentedControllChangedMapType:)])
{
//send the delegate function with the amount entered by the user
[self.delegate segmentedControllChangedMapType:mapType];
}
[self dismissModalViewControllerAnimated:YES];
}
MapsViewController.h
#import "MapBackgroundViewController.h"
@class MapBackgroundViewController;
@interface MapsViewController : UIViewController<MKMapViewDelegate,
UISearchBarDelegate, ChangeMapTyp >{
IBOutlet MKMapView *map;
}
@property (nonatomic, retain) IBOutlet MKMapView *map;
@end
MapsViewController.m(由于某种原因,以下方法永远不会被调用)
- (void)segmentedControllChangedMapType: (MKMapType) type{
map.mapType = type;
}
答案 0 :(得分:6)
在MapBackgroundViewController
中,您已将delegate
属性设置为self
,因此代理人为self
- (MapBackgroundViewController
),因此当您执行检查时{ {1}}它返回if([self.delegate respondsToSelector:@selector(segmentedControllChangedMapType:)])
,因为NO
(self.delegate
,即self
)未实现此方法。如果您希望MapBackgroundViewController
成为委托人,则在MapsViewController
中,您必须拥有MapBackgroundViewController
的实例(例如,名为MapsViewController
),然后设置myMapsViewController
}。