1

Based on https://medium.com/better-programming/swift-3-creating-a-custom-view-from-a-xib-ecdfe5b3a960, this is a common technique, to build a custom view via XIB.

import UIKit

class CustomView: UIView {
  @IBOutlet var contentView: UIView!
  @IBOutlet weak var mainLabel: UILabel!
  
  override init(frame: CGRect) {
    super.init(frame: frame)
    commonInit()
  }
  
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commonInit()
  }
  
  private func commonInit() {
    Bundle.main.loadNibNamed("CustomView", owner: self, options nil)
    addSubview(contentView)
    contentView.frame = self.bounds
    contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
  }
}

We will end up with the following custom view.

|-----------------------|
|   CustomView UIView   |
| |-------------------| |
| |  Content UIView   | |
| | |---------------| | |
| | |   UILabel     | | |
| | |---------------| | |
| |                   | |
| |-------------------| |
|                       |
|-----------------------|

However, since custom view itself is already an UIView, isn't it seem redundant, to have yet another UIView in itself?

Having a UIView (contentView) in another UIView (CustomView) seem serve no real purpose other than slowing down UI performance.

Isn't it will be better, if we can have something as following?

|-----------------------|
|   CustomView UIView   |
|   |---------------|   |
|   |   UILabel     |   |
|   |---------------|   |
|                       |
|-----------------------|

In Android ecosystem, we may solve this by using merge tag. Its description is as follow.

The tag helps eliminate redundant view groups in your view hierarchy when including one layout within another. For example, if your main layout is a vertical LinearLayout in which two consecutive views can be re-used in multiple layouts, then the re-usable layout in which you place the two views requires its own root view. However, using another LinearLayout as the root for the re-usable layout would result in a vertical LinearLayout inside a vertical LinearLayout. The nested LinearLayout serves no real purpose other than to slow down your UI performance.

Is there anything equivalent, when we are building custom view using XIB?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • You don't need the content view. Check this, there are some hints in the answers: https://stackoverflow.com/questions/24857986/load-a-uiview-from-nib-in-swift – Andreas Oetjen Aug 25 '20 at 06:54

0 Answers0