Swift 4:什么相当于以编程方式加载nib文件,没有故事板?

时间:2017-10-13 10:59:25

标签: swift storyboard mapkit

我在网上找到的一些代码非常适合我的项目。问题是我根本不使用故事板。我没有使用故事板文件来创建UIView (CustomCallOutView) ,而是创建一个带有UIView子类的类。这是需要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)
}

2 个答案:

答案 0 :(得分:0)

假设CustomCalloutView没有做任何复杂的事情:

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

答案 1 :(得分:0)

如果要创建加载 nib 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)
    }
}    

要添加自定义视图,您只需使用YourViewWithNib(frame: aFrame)或在任何XIB或Storyboard中添加YourViewWithNib视图。