Warning: file_put_contents(/datas/wwwroot/jiajiahui/core/caches/caches_template/2/default/show.php): failed to open stream: Permission denied in /datas/wwwroot/jiajiahui/core/libraries/classes/template_cache.class.php on line 55

Warning: chmod(): Operation not permitted in /datas/wwwroot/jiajiahui/core/libraries/classes/template_cache.class.php on line 56
Swift 4:相当于以编程方式加载nib文件,没有故事板? - 源码之家

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

问题描述:

我有一些代码,我在网上找到,完全适合我的项目。问题是我根本不使用故事板。而不是使用故事板文件来创建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) 
} 

假设CustomCalloutView不会做任何事情复杂:

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

如果你想创建一个的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视图。