我有一些代碼,我在網上找到,完全適合我的項目。問題是我根本不使用故事板。而不是使用故事板文件來創建UIView (CustomCallOutView)
,我只是創建一個類與UIView的子類。這是需要一個nib文件的代碼,但我不想使用它們。我如何實現這一目標?代碼如下。謝謝!Swift 4:相當於以編程方式加載nib文件,沒有故事板?
func mapView(_ mapView: MKMapView,
didSelect view: MKAnnotationView)
{
// 1
if view.annotation is MKUserLocation
{
// Don't proceed with custom callout
return
}
// 2
let starbucksAnnotation = view.annotation as! StarbucksAnnotation
let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil)
let calloutView = views?[0] as! CustomCalloutView
calloutView.starbucksName.text = starbucksAnnotation.name
calloutView.starbucksAddress.text = starbucksAnnotation.address
calloutView.starbucksPhone.text = starbucksAnnotation.phone
calloutView.starbucksImage.image = starbucksAnnotation.image
let button = UIButton(frame: calloutView.starbucksPhone.frame)
button.addTarget(self, action: #selector(ViewController.callPhoneNumber(sender:)), for: .touchUpInside)
calloutView.addSubview(button)
// 3
calloutView.center = CGPoint(x: view.bounds.size.width/2, y: -calloutView.bounds.size.height*0.52)
view.addSubview(calloutView)
mapView.setCenter((view.annotation?.coordinate)!, animated: true)
}