Хобрук: Ваш путь к мастерству в программировании

РЕДАКТИРОВАНИЕ: выноски аннотаций MapKit. Отрегулируйте размер UIPopoverController

Извините, я прочитал кучу руководств по созданию пользовательской выноски для аннотации MapKit. Он работает с NSLog, но я не могу отображать информацию в выносках.

У меня на карте есть два типа значков. Это мой метод viewForAnnotation:

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {

    if (! [annotation isKindOfClass:[IGAMapAnnotation class]]) {
        return nil;
    }

    IGAMapAnnotation *myLocation = (IGAMapAnnotation *) annotation;

    self.typeIsFix = [myLocation.navaidType isEqualToString:@"FIX"];
    self.typeIsPort = [myLocation.navaidType isEqualToString:@"PORT"];

    int planeImageViewTag = 42;

    NSString *reuseId;

    if (self.typeIsPort)
        reuseId = @"IGAMapAnnotationPort";

    else if (self.typeIsFix)
        reuseId = @"IGAMapAnnotationFix";

    else
        reuseId = @"IGAMapAnnotationOther";


    MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];

    if (annotationView == nil)
    {
        annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
        annotationView.enabled = YES;

        UIButton *annotationInfo = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        annotationView.rightCalloutAccessoryView = annotationInfo;
        annotationView.canShowCallout = YES;


        if (self.typeIsPort)
        {
            annotationView.image = [UIImage imageNamed:@"mapPORT.png"];
            annotationView.centerOffset = CGPointMake(0, 0);

        }

        else if (self.typeIsFix)
        {
            annotationView.image = [UIImage imageNamed:@"mapFIX.png"];
            annotationView.centerOffset = CGPointMake(0, 0);

        }

        else
            return nil;
    }

    else
    {
        annotationView.annotation = annotation;
    }

    return annotationView;
}

Тогда у меня есть метод calloutAccessoryControlTapped

- (void)mapView:(MKMapView *)mapview annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    IGAAnnotationInfoViewController *popOverCallout = [[IGAAnnotationInfoViewController alloc]init];

    UIPopoverController *popOver = [[UIPopoverController alloc] initWithContentViewController:popOverCallout];

    popOver.popoverContentSize = CGSizeMake(300, 200);

    [popOver presentPopoverFromRect:view.bounds
                             inView:view
           permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

Я также создал UIViewController, который назначил UIPopoverController.

Теперь, когда я нажимаю кнопку в аннотации, я вижу пробел для текста. Здорово. Если я назначаю текст метке в UIViewController, он также отлично работает (это мой UIViewController.m):

- (void)viewDidLoad {
    [super viewDidLoad];

    txtCallout = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 300, 200) ];
    txtCallout.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:(14.0)];
    txtCallout.numberOfLines = 0;
    txtCallout.clipsToBounds = YES;
    txtCallout.backgroundColor = [UIColor clearColor];
    txtCallout.textColor = [UIColor blackColor];
    txtCallout.textAlignment = NSTextAlignmentLeft;
    txtCallout.text = @"text\ntext\ntext";
    [self.view addSubview:txtCallout];
}

Но как мне вставить текст из моего метода аннотации? Также текст должен отличаться в зависимости от типа значка, например @ "PORT, PORT" или @ "FIX, FIX". Как это сделать?

РЕДАКТИРОВАТЬ:

Мне удалось отобразить выноски с переданной необходимой информацией. Моя последняя проблема в том, что иногда моя выноска состоит из 3 строк, иногда - до 15. Как можно сделать так, чтобы выноска автоматически подстраивалась под количество строк в моей строке? Должен ли я изменить свой popoverContentSize или размер моей метки в UIViewController?

Большое спасибо!


Ответы:


1

Я выяснил, как настроить выноску MK Annotation на UILabel.

Реализуйте метод calloutAccessoryControlTapped.

- (void)mapView:(MKMapView *)mapview annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    // OPTIONAL: Deselecting Annotation View when Callout is tapped
    //[mapview deselectAnnotation:view.annotation animated:YES];

    NSString *calloutDetails;

    IGAMapAnnotation *annotationTapped = (IGAMapAnnotation *)view.annotation;

    calloutDetails = [NSString stringWithFormat:@"YOUR TEXT:\nYOURTEXT\n"];

    // Declare and initialize the UIViewController that has the label to contain the callout information
    IGAAnnotationInfoViewController *detailViewController = [[IGAAnnotationInfoViewController alloc]initWithText:calloutDetails];

    UIPopoverController *popOver = [[UIPopoverController alloc] initWithContentViewController:detailViewController];

    // Size of the UIPopoverController = size of the label + 40 pts
    popOver.popoverContentSize = CGSizeMake(detailViewController.txtCallout.frame.size.width+40,detailViewController.txtCallout.frame.size.height+40);

    // Show popover controller
    [popOver presentPopoverFromRect:view.bounds
                             inView:view
           permittedArrowDirections:UIPopoverArrowDirectionAny
                           animated:YES];
}

Теперь IGAAnnotationInfoViewController.h

@interface IGAAnnotationInfoViewController : UIViewController   {
    CGRect calloutSize;
}

@property (strong,nonatomic) NSString *calloutInformation;
@property (strong,nonatomic) IGACalloutLabel *txtCallout;

-(IGAAnnotationInfoViewController*) initWithText : (NSString*) calloutText;

IGAAnnotationInfoViewController.m

 @implementation IGAAnnotationInfoViewController

 @synthesize calloutInformation,txtCallout;

-(IGAAnnotationInfoViewController*) initWithText : (NSString*) calloutText {
    self = [super init];

    if ( self ) {
        calloutInformation = calloutText;

        // Creating a label that will display the callout information (passed from IGAAcarasViewController - Map Annotation)
        txtCallout = [[IGACalloutLabel alloc] initWithFrame:CGRectMake(20, 20, 0, 0)];

        txtCallout.lineBreakMode = NSLineBreakByWordWrapping;
        txtCallout.numberOfLines=0;
        txtCallout.backgroundColor = [UIColor clearColor];
        txtCallout.textColor=[UIColor blueColor];
        txtCallout.text = calloutInformation;
        [txtCallout drawTextInRect:CGRectMake(10,10,0,0)];

        [txtCallout sizeToFit];
        [self.view addSubview:txtCallout];
    }

    return self;
}

Наконец, создайте подкласс класса UILabel:

implementation IGACalloutLabel

@synthesize topInset, leftInset, bottomInset, rightInset;

- (void)drawTextInRect:(CGRect)rect
{
    UIEdgeInsets insets = {topInset,leftInset,bottomInset,rightInset};

    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

С уважением,

17.12.2014
Новые материалы

Создание кнопочного меню с использованием HTML, CSS и JavaScript
Вы будете создавать кнопочное меню, которое имеет состояние наведения, а также позволяет вам выбирать кнопку при нажатии на нее. Финальный проект можно увидеть в этом Codepen . Шаг 1..

Внедрите OAuth в свои веб-приложения для повышения безопасности
OAuth — это широко распространенный стандарт авторизации, который позволяет приложениям получать доступ к ресурсам от имени пользователя, не раскрывая его пароль. Это позволяет пользователям..

Классы в JavaScript
class является образцом java Script Object. Конструкция «class» позволяет определять классы на основе прототипов с чистым, красивым синтаксисом. // define class Human class Human {..

Как свинг-трейдеры могут использовать ИИ для больших выигрышей
По мере того как все больше и больше профессиональных трейдеров и активных розничных трейдеров узнают о возможностях, которые предоставляет искусственный интеллект и машинное обучение для улучшения..

Как построить любой стол
Я разработчик программного обеспечения. Я люблю делать вещи и всегда любил. Для меня программирование всегда было способом создавать вещи, используя только компьютер и мое воображение...

Обзор: Машинное обучение: классификация
Только что закончил третий курс курса 4 часть специализации по машинному обучению . Как и второй курс, он был посвящен низкоуровневой работе алгоритмов машинного обучения. Что касается..

Разработка расширений Qlik Sense с qExt
Использование современных инструментов веб-разработки для разработки крутых расширений Вы когда-нибудь хотели кнопку для установки переменной в приложении Qlik Sense? Когда-нибудь просили..