MKMapView custom callOutView with auto layout iOS

2019-08-05 06:43发布

Hej Folks,

my apps crashes on a MKMapView under iOS 6 if I use auto layout for the callout view. With iOS 7 this works fine.

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
CustomMapAnnotation *annotation = (CustomMapAnnotation *)view.annotation;

if([annotation isKindOfClass:[CustomMapAnnotation class]]) {
    CustomMapCalloutView *calloutView = [CustomMapCalloutView new];
    calloutView.translatesAutoresizingMaskIntoConstraints = NO;

    calloutView.titleLabel.text = annotation.titleText;
    calloutView.subTitleLabel.text = annotation.subTitleText;
    calloutView.distanceTextLabel.text = annotation.distanceText;

    [view addSubview:calloutView];

    NSDictionary *viewsDictionary = @{@"callOutView": calloutView};
    NSArray *hConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[callOutView(150)]" options:0 metrics:nil views:viewsDictionary];
    NSArray *vConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[callOutView(50)]" options:0 metrics:nil views:viewsDictionary];

    NSLayoutConstraint *xConstraint = [NSLayoutConstraint constraintWithItem:calloutView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
    NSLayoutConstraint *yConstraint = [NSLayoutConstraint constraintWithItem:calloutView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0];

    [view addConstraint:xConstraint];
    [view addConstraint:yConstraint];

    [view addConstraints:hConstraints];
    [view addConstraints:vConstraints];
}}

The console shows the following error:

* Assertion failure in -[MKAnnotationView layoutSublayersOfLayer:], /SourceCache/UIKit_Sim/UIKit-2380.17/UIView.m:5776 2013-10-27 13:39:18.519 PartySmarty[9825:907] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. MKAnnotationView's implementation of -layoutSubviews needs to call super.'

Can somebody give me a hint where the problem is? The CustomCalloutView works also with auto layout and I don't overwrite layoutSubviews within.

1条回答
手持菜刀,她持情操
2楼-- · 2019-08-05 07:21

This SO Answer points me in the right direction. I create a category on the MKAnnotationView, override the layoutSubviews method and call the super method.

This works also on iOS 7.

查看更多
登录 后发表回答