[SWIFT] How to load UI created by Xib file into View

You want to make the restrictions of AutoLayout as simple as possible. By loading Xib into View, the constraints in ViewController are made simpler! And simplify.

First, place the View in sampleViewController.Xib. スクリーンショット 2020-11-14 12.09.12.png

After placing the View like this, create a Swift file and a View Xib file.

Swift file スクリーンショット 2020-11-14 11.55.32.png View Xib file スクリーンショット 2020-11-15 21.04.17.png

Let's use the same file name! !! (Named sampleHomeView this time)

Write the code in sampleHomeView.swift. This is OK with copy and paste.

sampleHomeView.swift


import UIKit

class sampleHomeView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        loadView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        loadView()
    }
    
    private func loadView() {
        let className = String(describing: type(of: self))
        let view: UIView = Bundle.main.loadNibNamed(className, owner: self, options: nil)?.first as? UIView ?? UIView()
        view.frame = bounds
        addSubview(view)
    }
}

By writing this code, you can set the class of File's Owner and load it into View. Select File's Owner in sampleHomeView.Xib and set Class to sampleHomeView. スクリーンショット 2020-11-15 20.51.38.png

Then place the UI parts in sampleHomeView.Xib. (Place Button this time) スクリーンショット 2020-11-14 12.01.59.png

Next, set sampleView.Xib. Select the View you placed first and set the Class of CustomClass to sampleHomeView. スクリーンショット 2020-11-15 20.55.59.png Now you can load Xib into View. However, in this state, we do not know that it is loaded in View, so let's build it! !! スクリーンショット 2020-11-14 12.09.28.png

You could load it with this (^ ^) By doing this, it seems that the layout of UI parts can be simplified.

Recommended Posts

How to load UI created by Xib file into View
How to load a Spring upload file and view its contents
How to output CSV created by Rails to S3
Incorporate View created with Swift UI into ViewController
[Rails] How to load JavaScript in a specific view
[Ruby] How to split each GraphQL query into a file
How to develop separately into Xib files without using Storyboard
How to "hollow" View on Android
How to convert erb file to haml
[Beginner] How to delete NO FILE
[Xcode] How to add a README.md file
How to prevent duplicate processing by addEventListener
How to use binding.pry for view files
[Java] How to use the File class
How to delete the wrong migration file
How to add jar file in ScalaIDE
How to achieve file download with Feign
How to split Spring Boot message file
How to achieve file upload with Feign
[Rails] How to translate devise into Japanese