How to use custom view with in swift?

create custom uiview programmatically swift 4
custom uiview swift 4
load viewcontroller from xib swift 4
custom uiview in storyboard
reusable uiview swift
custom uiview with autolayout
uiview custom properties
custom uiview with xib objective-c

I want to add a custom view in TableViewHeader. But when I run the following code it creates a Cycle and app stuck for any user interaction.

import UIKit
class ExpandableView: UIView {

    @IBOutlet weak var userImgView: UIImageView!
    @IBOutlet weak var userNamelbl: UILabel!
    @IBOutlet weak var countLbl: UILabel!
    @IBOutlet weak var rightArrowImgView: UIImageView!
    var isExpanded = false
    var contentView: UIView!
    @IBOutlet weak var checkMarkView: UIImageView!

    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    public override init(frame: CGRect) {
        super.init(frame: frame)
        setUpView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUpView()
    }

    private func setUpView() {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: "ExpandableView", bundle: bundle)
        self.contentView = nib.instantiate(withOwner: self, options: nil).first as? UIView
        addSubview(contentView)
        contentView.center = self.center
        contentView.autoresizingMask = []
        contentView.translatesAutoresizingMaskIntoConstraints = true
    }
}

I am using it as follows:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 60)
    let expandabelView = ExpandableView(frame: frame)
    return expandabelView
}

And it shows following error on run.


There may be many other ways, but I recommend you to make your ExpandableView reusable to improve performance.


First of all, simplify your ExpandableView class:

import UIKit

class ExpandableView: UITableViewHeaderFooterView {
    @IBOutlet weak var userImgView: UIImageView!
    @IBOutlet weak var userNamelbl: UILabel!
    @IBOutlet weak var countLbl: UILabel!
    @IBOutlet weak var rightArrowImgView: UIImageView!
    var isExpanded = false

    @IBOutlet weak var checkMarkView: UIImageView!
}

Please do not miss that the superclass is UITableViewHeaderFooterView, not UIView.

Second, check the settings of your ExpandableView.xib:

The Custom View setting of the defined view needs to be ExpandableView.

When you cannot choose ExpandableView from the pull down list, you may need to input manually. Do not forget to check Inherit Module From Target.

The Custom View setting of the File's Owner needs to be empty.

If there's some class already set, remove it manually.

Confirm all Outlets are connected properly to your ExpandableView.

(You should better reconnect them all, after you modified your xib.)

You may need to re-structure your view hierarchy and/or constraints.

Third, modify your view controller holding the table view.

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        tableView.delegate = self
        tableView.dataSource = self
        //...
        let nib = UINib(nibName: "ExpandableView", bundle: nil)
        tableView.register(nib, forHeaderFooterViewReuseIdentifier: "ExpandableView")
        tableView.estimatedSectionHeaderHeight = 60
        tableView.sectionHeaderHeight = UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let expandabelView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "ExpandableView")
        // Frame size should be represented with constraints.
        return expandabelView
    }

Swift, The directions below are a basic walk through using Swift. Add custom view files. The following two files will form your custom view: .xib file to  Custom View by use of xib in swift 1: First create a single view application project.. 2: Create the .xib file (like CustomUIView.xib). Now you want to create the new user interface like .xib file. Right 3: Design your customView user interface in interface xcode (use the Auto Layout


When you create custom UIView, it should follow this if you want to use it init with frame.

class CustomView: UIView {
    //This should be contentview of your xib
    @IBOutlet var view: UIView!

    let nibName = "CustomView"

    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        xibSetup()
    }

    private func xibSetup()
    {
        Bundle.main.loadNibNamed(nibName, owner: self, options: nil)
        self.view.autoresizesSubviews = true
        self.translatesAutoresizingMaskIntoConstraints = false

        self.addSubview(self.view)
        self.view.frame = self.frame


    }

}

Creating custom views in iOS for multiple reuse - Suragch, class CustomView: UIView { //we use lazy properties for each view lazy var addButton: UIButton = { let addButton = UIButton(type: .contactAdd) One of the core tenets of SwiftUI is composition, which means it’s designed for us to create many small views then combine them together to create something bigger. This allows us to re-use views on a massive scale, which means less work for us. Even better, combining small subviews has virtually no runtime overhead, so we can use them freely.


Since you need to load view from nib, just load it and then add subview to your view. Then set content view's frame and set autoresizing mask of content view correctly

private func setUpView() {
    Bundle.main.loadNibNamed("ExpandableView", owner: self, options: nil)
    addSubview(contentView)
    contentView.frame = bounds
    contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}

Custom UIView in Swift done right - Noteworthy, Also, make sure that the class for your view is selected as Subview . How to initialise a UIView Class with a xib file in Swift, iOS Obj-C and Swift versions, including using the custom classes within Interface Builder. Swift — Creating a Custom View From a XIB (Updated for Swift 5) Creating a custom view is often easiest in a XIB file, where you can visualize, layout, and edit the look and feel of what you’re. Working on the main conversation view.


Programatically adding custom view to another view, I like to create my iOS custom views using .xib files because they require less In Swift, @NSManaged is how you tell the compiler that this is  View controller containment has been an essential part of UIKit ever since the early days of the iPhone. With classes like UINavigationController and UITabBarController, container view controllers in many ways define how we interact with most apps on iOS and how their various screens are structured.


Creating iOS Custom Views in UIKit, Do you want to learn how to load a xib file to create a custom view object? Well, this UIKit tutorial is just for you written in Swift. Fully updated for Xcode 11.5. SwiftUI doesn’t have a built-in way to animate text size, but we can create an AnimatableModifier that makes the effect possible. This is not the same as using a simple scaleEffect() modifier – that will cause your text to become blurry when scaled up, whereas this custom animation will re-render your text correctly so it looks great at all sizes.


IOS 12, Swift 4.2, Tutorial : How to make custom view with Xib file , This allows us to re-use views on a massive scale, which means less work for us. Even better, combining small subviews has virtually no  But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly: customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50)) self.view.addSubview(customView) Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.