How to embed a custom view xib in a storyboard scene?

前端 未结 11 747
生来不讨喜
生来不讨喜 2021-01-29 21:33

I\'m relatively new in the XCode/iOS world; I\'ve done some decent sized storyboard based apps, but I didn\'t ever cut me teeth on the whole nib/xib thing. I want to use the sam

11条回答
  •  不知归路
    2021-01-29 22:04

    • Create xib file File > New > New File > iOS > User Interface > View
    • Create custom UIView class File > New > New File > iOS > Source > CocoaTouch
    • Assign the xib file's identity to the custom view class
    • In viewDidLoad of the view controller initialize the xib and its associated file using loadNibNamed: on NSBundle.mainBundle and the first view returned can be added as a subview of self.view.
    • The custom view loaded from the nib can be saved to a property for setting the frame in viewDidLayoutSubviews. Just set the frame to self.view's frame unless you need to make it smaller than self.view.

      class ViewController: UIViewController {
      
          weak var customView: MyView!
      
          override func viewDidLoad() {
              super.viewDidLoad()
              self.customView = NSBundle.mainBundle().loadNibNamed("MyView", owner: self, options: nil)[0] as! MyView
              self.view.addSubview(customView)
              addButtonHandlerForCustomView()
          }
      
          private func addButtonHandlerForCustomView() {
              customView.buttonHandler = {
                  [weak self] (sender:UIButton) in
                  guard let welf = self else {
                      return
                  }
                  welf.buttonTapped(sender)
              }
          }
      
          override func viewDidLayoutSubviews() {
              self.customView.frame = self.view.frame
          }
      
          private func buttonTapped(button:UIButton) {
      
          }
      }
      
    • Also, if you want to talk back from the xib to your UIViewController instance then create a weak property on the custom view's class.

      class MyView: UIView {
      
          var buttonHandler:((sender:UIButton)->())!
      
          @IBAction func buttonTapped(sender: UIButton) {
              buttonHandler(sender:sender)
          }
      }
      

    Here's the project on GitHub

提交回复
热议问题