我有一个带有textField的mapkit,用户可以在其中添加自己的点;程序运行,但当我输入内容并按回车键时,没有任何反应,没有设置新的引脚。谁能告诉我我做错了什么? Pin类的代码
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface Pin : NSObject <MKAnnotation>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSDate *createdAt;
@property (nonatomic) CLLocationCoordinate2D coordinate;
- (instancetype)initWithName:(NSString*)name andCoord:(CLLocationCoordinate2D)coord;
+ (instancetype)spotWithName:(NSString*)name andCoord:(CLLocationCoordinate2D)coord;
- (NSString*)title;
@end
Pin.m:
#import "Pin.h"
@implementation Pin
- (instancetype)initWithName:(NSString *)name andCoord:(CLLocationCoordinate2D)coord {
if (self = [super init]) {
_name = name;
_coordinate = coord;
_createdAt = [NSDate date];
}
return self;
}
+ (instancetype)spotWithName:(NSString *)name andCoord:(CLLocationCoordinate2D)coord {
return [[Pin alloc] initWithName:name andCoord:coord];
}
- (NSString *)title {
return _name;
}
- (NSString *)subtitle {
return [_createdAt description];
}
- (NSString *)description {
return [NSString stringWithFormat:@"%@ [%@]", _name, _createdAt];
}
查看控制器实施:
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import "Pin.h"
@interface ViewController ()<MKMapViewDelegate, CLLocationManagerDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UILabel *latitude;
@property (weak, nonatomic) IBOutlet UITextField *nameInput;
@property (strong, nonatomic) CLLocationManager *locationManager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_mapView.showsUserLocation=YES;
_mapView.showsBuildings=YES;
_locationManager = [[CLLocationManager alloc] init];
[_locationManager requestAlwaysAuthorization];
[_locationManager startUpdatingLocation];
_mapView.delegate = self;
_locationManager.delegate=self;
}
- (IBAction)userLoc:(UIButton *)sender {
MKCoordinateRegion region = MKCoordinateRegionMake(_mapView.userLocation.coordinate, MKCoordinateSpanMake( 37.78583400, 122.40641700));
[_mapView setRegion:region animated:NO];
}
#pragma mark - CCLocationManagerDelegate methods
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLLocation *loc = [locations objectAtIndex:0];
_latitude.text = [NSString stringWithFormat:@"%g º", loc.coordinate.latitude];
}
#pragma mark - MKMapViewDelegate methods
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
_mapView.centerCoordinate = userLocation.location.coordinate;
}
#pragma mark - UITextFieldDelegate methods
- (BOOL)textFieldShouldReturn:(UITextField *)nameInput {
Pin *pin = [Pin spotWithName:nameInput.text andCoord:_mapView.userLocation.coordinate];
[_mapView addAnnotation:pin];
nameInput.text = @"";
[nameInput resignFirstResponder];
return NO;
}
@end
答案 0 :(得分:0)
基本上,缺少一行:
_nameInput.delegate=self;
如果我在实现上有一个UITextfield协议,我必须分配它的委托,在这种情况下,它是自己的,如mapKit和CCLocation Manager