因为我们项目中是多地图模式的 之前产品看到别的地图上有用户位置指向角 我们苹果地图咋就没有捏
之后查看MKMapView API 确实没有把MKModernUserLocationView暴露出来给开发者使用 所以只好自己写一个贴在上面啦
先看效果
实现
.h文件
#import <UIKit/UIKit.h>
@interface LHUserLocationHeadingView : UIView
- (void)startUpdatingHeading;
- (void)stopUpdatingHeading;
@end
.m文件
#import "LHUserLocationHeadingView.h"
#import <CoreLocation/CoreLocation.h>
@interface LHUserLocationHeadingView()<CLLocationManagerDelegate>
@property (nonatomic, strong) UIImageView *arrowImageView;
@property (nonatomic, strong) CLLocationManager *locationManager;
@end
@implementation AAUserLocationHeadingView
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self commonInit];
}
return self;
}
- (UIImageView *)arrowImageView
{
if (_arrowImageView == nil) {
_arrowImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"xz_loction_heading_arrow"]];
}
return _arrowImageView;
}
- (CLLocationManager *)locationManager
{
if (_locationManager == nil) {
_locationManager = [[CLLocationManager alloc]init];
_locationManager.delegate = self;
}
return _locationManager;
}
- (void)commonInit{
self.backgroundColor = [UIColor clearColor];
self.arrowImageView.frame = self.frame;
[self addSubview:self.arrowImageView];
[self startUpdatingHeading];
}
- (void)startUpdatingHeading{
[self.locationManager startUpdatingHeading];
}
- (void)stopUpdatingHeading{
[self.locationManager stopUpdatingHeading];
}
#pragma mark -- CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
if (newHeading.headingAccuracy < 0) return;
CLLocationDirection heading = newHeading.trueHeading > 0 ? newHeading.trueHeading : newHeading.magneticHeading;
CGFloat rotation = heading/180 * M_PI;
self.arrowImageView.transform = CGAffineTransformMakeRotation(rotation);
}
使用
在Map初始化时会掉用这个代理方法 可以判断是否时Map的私有对象UserLocationView 添加自定义的View在其上 切图找设计要 或者你随便加一个看一下效果
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray<MKAnnotationView *> *)views{
if ([views.lastObject isKindOfClass:NSClassFromString(@"MKModernUserLocationView")]) {
AAUserLocationHeadingView *headingView = [[AAUserLocationHeadingView alloc]initWithFrame:CGRectMake(0, 0, 36, 36)];
headingView.center = CGPointMake(views.lastObject.width/2, views.lastObject.height / 2);
headingView.tag = 312;
if (![views.lastObject viewWithTag:312]) {
[views.lastObject addSubview:headingView];
_userHeadingView = headingView;
}
}
}
//在Map不在屏幕显示时记得停止获取方向 进入时再开始
[_userHeadingView startUpdatingHeading];
[_userHeadingView stopUpdatingHeading];
//在跟随模式下记得隐藏 其他模式下显示
_userHeadingView.hidden = YES;