2016-05-25 2 views
2

Есть ли способ создания многострочных аннотаций?SWIFT 2: многострочный MKPointAnnotation

Вот мой код:

1) Мой customAnnotation класс

import UIKit 
import MapKit 

class CustomAnnotation: NSObject, MKAnnotation { 

    var title: String? 
    var subtitle: String? 
    var address: String = "" 
    var phoneNumber: String = "" 
    var workingHours: String = "" 
    var coordinate: CLLocationCoordinate2D 


    init( title: String, 
      subtitle: String, 
      address: String, 
      phoneNumber: String, 
      workingHours: String, 
      coordinate: CLLocationCoordinate2D){ 

     self.title = title 
     self.subtitle = subtitle 
     self.address = address 
     self.phoneNumber = phoneNumber 
     self.workingHours = workingHours 
     self.coordinate = coordinate 

     super.init() 
    } 
} 

2) мой вид контроллер с картой:

класс MapViewController: UIViewController, MKMapViewDelegate {

@IBOutlet weak var theMapView: MKMapView! 

override func viewDidLoad() { 
    super.viewDidLoad() 


      let latitude: CLLocationDegrees = 54.685290 
      let longitude : CLLocationDegrees = 25.279661 

      let latDelta : CLLocationDegrees = 0.2 
      let lonDelta : CLLocationDegrees = 0.2 

      let theSpan : MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) 

      let branchLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) 

      let theRegion : MKCoordinateRegion = MKCoordinateRegionMake(branchLocation, theSpan) 


      let annotation = CustomAnnotation(title: "Brach1", subtitle: "some text for B1", address: "address str 12-12", phoneNumber: "123 321 123", workingHours: "00 - 24", coordinate: branchLocation) 


      self.theMapView.setRegion(theRegion, animated: true) 

      self.theMapView.addAnnotation(annotation) 

     } 


override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 

} 


func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 

    let identifier = "MyPin" 

    if annotation.isKindOfClass(MKUserLocation) { 
     return nil 
    } 

    var annotationView: MKPinAnnotationView? = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView 

    if annotationView == nil { 

     annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) 
     annotationView?.canShowCallout = true 

     let multiLineView = UIView(frame: CGRectMake(0, 0, 100, 40)) 

     let label1 = UILabel(frame: CGRectMake(0,0,100,20)) 
     label1.text = "Some text1" 
     multiLineView.addSubview(label1) 

     let label2 = UILabel(frame: CGRectMake(0,20,100,20)) 
     label2.text = "some text2" 
     multiLineView.addSubview(label2) 

     annotationView!.rightCalloutAccessoryView = multiLineView 

    } else { 
     annotationView!.annotation = annotation 
    } 
return annotationView 
} 

}

Что я получаю:

enter image description here

Если я хотел бы использовать

annotationView!.leftCalloutAccessoryView = multiLineView 

Я хотел бы получить:

enter image description here

я не нашел каких-либо других методов. Я хотел бы ожидать что-то вроде bottomCalouttAccessoryView, чтобы получить что-то вроде:

enter image description here

Это очень проводная для меня, что высота аннотацию не исправимо. (вот почему мои три таблицы не подходят даже там) Я пытался играть с авторезистентными методами аннотации, но не повезло :(

+0

вы проверить мой код. –

ответ

0

Подзаголовок - это строка, которая печатает на одну строчную метку, вы бы вероятно, придется сделать подкласс, чтобы добавить несколько строк

+0

Вы можете добавить более подробную информацию о том, как это сделать? – Almazini

1

вы смотрели на:. How to display 2 lines of text for subtitle of MKAnnotation and change the image for the button on the right?

особенно этой части (я преобразовал его в Swift для вас)

var multiLineView= UIView(frame: CGRectMake(0, 0, 23, 23)) 
    multiLineView.addSubview(lable1) 
    multiLineView.addSubview(lable2) 
    annotationView.leftCalloutAccessoryView = multiLineView 

UPDATE

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView! { 

var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier("pin") 

if pinView == nil { 
    pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin") 
    pinView!.canShowCallout = true 

    // create a new View 
    var multiLineView= UIView(frame: CGRectMake(0, 0, 23, 23)) 
    // add all the labels you need here 
    let label1 = UILabel(frame: CGRectMake(0,10,10,10)) 
    label1.text = "Some text" 
    multiLineView.addSubview(label1) 
    let label2 = UILabel(frame: CGRectMake(0,20,10,10)) 
    label2.text = "some text" 
    multiLineView.addSubview(label2) 
    pinView!.leftCalloutAccessoryView = multiLineView 


} 
else { 
    pinView!.annotation = annotation 
} 

return pinView 

}

+0

поэтому, если я объявляю такие метки: «let lable1 = UIView()« Я могу использовать их в качестве аргумента в addSubview. но компилятор все равно выдает ошибку: «значение типа MKPointAnnotation не имеет члена leftCalloutAccessoryView» «Что я делаю неправильно? Не уверен, что я хорошо понимаю код в объективе-c из вашей ссылки. – Almazini

+0

аннотация должна быть типа MKAnnotationView, а не MKPointAnnotation. например: let annotationView = MKAnnotationView().Чтобы создать lable, вы должны объявить следующее: let label1 = UILabel (frame: CGRectMake (0,0,10,10). Я отредактирую свой ответ, чтобы уточнить его. – Rob8861

+0

Когда я должен создать эту функцию и как она должна быть Я хотел бы изменить свой вопрос, чтобы добавить больше ясности в свой код. Может быть, вы могли бы сказать мне, где я должен использовать ваш код. спасибо – Almazini

0

плз использовать этот я программно установить NSLayoutConstraint.

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 

     let identifier = "MyPin" 

     if annotation.isKindOfClass(MKUserLocation) { 
      return nil 
     } 

     var annotationView: MKPinAnnotationView? = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView 

     if annotationView == nil { 

      annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) 
      annotationView?.canShowCallout = true 

       let label1 = UILabel(frame: CGRectMake(0, 0, 200, 21)) 
      label1.text = "Some text1 some text2 some text2 some text2 some text2 some text2 some text2" 
      label1.numberOfLines = 0 
       annotationView!.detailCalloutAccessoryView = label1; 

      let width = NSLayoutConstraint(item: label1, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 200) 
      label1.addConstraint(width) 


      let height = NSLayoutConstraint(item: label1, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 90) 
      label1.addConstraint(height) 



     } else { 
      annotationView!.annotation = annotation 
     } 
     return annotationView 
    } 


} 

и выход enter image description here

Смежные вопросы