Swift 4 Mapkit批注自定义用Xib文件调出

时间:2018-06-21 01:09:13

标签: ios swift mapkit swift4 mapkitannotation

我正在尝试在Swift 4下创建自定义注释标注。我在Google上待了几天,我发现的示例要么是Swift 2要么是Swift 3,我无法理解其中的某些部分。

我创建了一个xib视图文件及其控制器:

import UIKit
import MapKit

class ForHireAnnotationCallOut: UIView {

@IBOutlet weak var coImage: UIImageView!
@IBOutlet weak var coName: UILabel!
@IBOutlet weak var coServiceType: UILabel!
@IBOutlet weak var coExp: UILabel!
@IBOutlet weak var coHourlyRate: UILabel!
@IBAction func ocDetailsBtn(_ sender: Any) {

}
var coAnnotation = MKPointAnnotation()
internal var coData: User?{
    didSet{
        coName.text = coData?.name
        coServiceType.text = coData?.serviceType
        coExp.text = (coData?.exp.replacingOccurrences(of: "Years", with: "Yrs"))! + " Exp."
        coHourlyRate.text = coData?.hourlyRate

        self.layoutIfNeeded()
    }
}


internal var preferredContentSize:CGSize{

        return CGSize(width: 0, height: 0)

}

override init(frame: CGRect) {
    super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func awakeFromNib() {
    super.awakeFromNib()
}

}

用户结构包含:

public struct User: Equatable {
var uid: String
var name: String
var phone: String
var serviceType: String
var exp: String
var hourlyRate: String
var pictureUrl: String
}

自定义注释类:

public class myAnnotation: NSObject, MKAnnotation {
public var coordinate: CLLocationCoordinate2D
public var title: String?
public var subtitle: String?
var userKey: String?
public var exp: String?
public var hourlyRate: String?

override init() {
    self.coordinate = CLLocationCoordinate2D()
    self.title = nil
    self.subtitle = nil
    self.userKey = nil
    self.exp = nil
    self.hourlyRate = nil
}

}

我的理解是,为了进行自定义标注,您将需要使用mapView viewFor批注功能来使用xib视图。

我在@Babac的另一个线程中找到了一个示例,并在swift 4中将其修改为如下所示:

func mapView(_ mapView: MKMapView, viewFor annotation: myAnnotation) -> MKAnnotationView? {
// Don't want to show a custom image if the annotation is the user's location.
guard !(annotation is MKUserLocation) else {
    return nil
}

// Better to make this class property 
let annotationIdentifier = "AnnotationIdentifier" //<---not very sure why we need this

var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
    annotationView = dequeuedAnnotationView
    annotationView?.annotation = annotation
}
else {
    let av = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
    av.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
    annotationView = av
}

if let annotationView = annotationView {
    // Configure your annotation view here
    annotationView.canShowCallout = true
    annotationView.image = UIImage(named: "yourImage")
}

return annotationView
}

除了annotationIdentifier之外,我不知道在该函数中应在何处包含我的xib视图及其控制器以进行标注。另外,如何将这些值传递给xib视图控制器?

谢谢

0 个答案:

没有答案