2017-10-13 87 views
-2

我有一些代碼,我在網上找到,完全適合我的項目。問題是我根本不使用故事板。而不是使用故事板文件來創建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) 
} 

回答

0

假設CustomCalloutView不會做任何事情複雜:

let calloutView = CustomCalloutView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) 
0

如果你想創建一個的UIView子類是加載筆尖您可以使用以下方法:

class YourViewWithNib: UIView { 
    required init?(coder: NSCoder) { 
     super.init(coder: coder) 
     loadNib() 
    } 


    override init(frame: CGRect) { 
     super.init(frame: frame) 
     bounds = frame 
     loadNib() 
    } 

    func loadNib() { 
     let nib = Bundle.main.loadNibNamed(
      "YourNibFileName", 
      owner: self, 
      options: nil 
     ) 
     let view = nib![0] as! UIView 

     view.translatesAutoresizingMaskIntoConstraints = false 
     addSubview(view) 

     // if you are using autolayout 
     let views = ["nibView": view] 
     let hconstraints = NSLayoutConstraint.constraints(
      withVisualFormat: "H:|[nibView]|", 
      metrics: nil, 
      views: views 
     ) 
     NSLayoutConstraint.activate(hconstraints) 

     let vconstraints = NSLayoutConstraint.constraints(
      withVisualFormat: "V:|[nibView]|", 
      metrics: nil, 
      views: views 
     ) 
     NSLayoutConstraint.activate(vconstraints) 
    } 
}  

要添加您的自定義視圖, t可以使用YourViewWithNib(frame: aFrame)或在任何XIB或Storyboard中添加YourViewWithNib視圖。

相關問題