MKAnnotation Swift

前端 未结 1 986
名媛妹妹
名媛妹妹 2021-01-30 16:56

I am unsure how to annotate a map in the swift language. I don\'t know how to create the NSObject class. The following is code I tried but was unable to run:

imp         


        
相关标签:
1条回答
  • 2021-01-30 17:48
    1. All initialization methods in Swift must simply be "init"
    2. MKAnnotation requires that the object inherit from NSObjectProtocol. To do that, you should have your class inherit from NSObject
    3. You should declare your properties to match those of the MKAnnotation protocol
    4. You should not declare your parameters as Implicitly Unwrapped Optionals unless you really have to. Let the compiler check if something is nil instead of throwing runtime errors.

    This gives you the result:

    class MapPin : NSObject, MKAnnotation {
        var coordinate: CLLocationCoordinate2D
        var title: String?
        var subtitle: String?
    
        init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
            self.coordinate = coordinate
            self.title = title
            self.subtitle = subtitle
        }
    }
    
    0 讨论(0)
提交回复
热议问题