Thursday, February 2, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Swift

Custom UIView subclass from a xib file

learningcode_x1mckf by learningcode_x1mckf
October 3, 2022
in Swift
0
Custom UIView subclass from a xib file
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


You might also like

The abstract Vapor service factory design pattern

SwiftNIO tutorial – The echo server

Introducing – Vapor cheatsheet – The.Swift.Dev.

Loading xib information

Utilizing the contents of a xib file is a fairly rattling simple job to do. You need to use the next two strategies to load the contents (aka. the view hierarchy) of the file.


let view = UINib(nibName: "CustomView", bundle: .most important).instantiate(withOwner: nil, choices: nil).first as! UIView

view.body = self.view.bounds
self.view.addSubview(view)


The snippet above will merely instantiate a view object from the xib file. You may have a number of root objects within the view hierarchy, however this time let’s simply choose the primary one and use that. I assume that in 99% of the instances that is what you will want with a view to get your customized views. Additionally you may lengthen the UIView object with any of the options above to create a generic view loader. Extra on that later… 😊

This technique is fairly easy and low-cost, nonetheless there’s one little downside. You may’t get named pointers (retailers) for the views, however just for the foundation object. In case you are placing design parts into your display screen, that is effective, but when it’s essential show dynamic knowledge, you may wish to attain out for the underlying views as effectively. 😃

Customized views with retailers & actions

So the correct option to load customized views from xib information goes one thing like this:

Inside your customized view object, you instantiate the xib file precisely the identical means as I advised you proper up right here. 👆 The one distinction is that you just need not use the article array returned by the strategies, however it’s a must to join your view objects by the interface builder, utilizing the File’s Proprietor as a reference level, plus a customized container view outlet, that’ll comprise all the pieces you want. 🤨



class CustomView: View 

    
    @IBOutlet weak var containerView: UIView!

    
    @IBOutlet weak var textLabel: UILabel!

    override func initialize() 
        tremendous.initialize()

        
        let title = String(describing: kind(of: self))
        let nib = UINib(nibName: title, bundle: .most important)
        nib.instantiate(withOwner: self, choices: nil)

        
        self.addSubview(self.containerView)
        self.containerView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.containerView.topAnchor.constraint(equalTo: self.topAnchor),
            self.containerView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            self.containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            self.containerView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
        ])
    


So the initialize technique right here is simply loading the nib file with the proprietor of self. After the loading course of completed, your outlet pointers are going to be stuffed with correct values from the xib file. There may be one very last thing that we have to do. Even the views from the xib file are “programmatically” linked to our custom view object, however visually they are not. So now we have so as to add our container view into the view hierarchy. 🤐


If you wish to use your customized view object, you simply should create a brand new occasion from it – inside a view controller – and at last be happy so as to add it as a subview!

One phrase about bounds, frames aka. springs and struts: f*ckng UGLY! That is two phrases. They’re thought-about as a foul follow, so please use auto layout, I’ve a pleasant tutorial about anchors, they’re wonderful and studying them takes about quarter-hour. 😅


class ViewController: UIViewController 

    weak var customView: CustomView!

    override func loadView() 
        tremendous.loadView()

        let customView = CustomView()
        self.view.addSubview(customView)
        NSLayoutConstraint.activate([
            customView.topAnchor.constraint(equalTo: self.view.topAnchor),
            customView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            customView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            customView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
        ])
        self.customView = customView
    

    override func viewDidLoad() 
        tremendous.viewDidLoad()

        self.customView.textLabel.textual content = "Lorem ipsum"
    


That is it, now you could have a very working customized UIView object that masses a xib file with a view to use it is contents. Wasn’t so unhealthy, proper? 🤪

Yet another additional factor. When you do not prefer to deal with views programmatically otherwise you merely do not wish to fiddle with the loadView technique, simply take away it fully. Subsequent put the @IBOutlet key phrase proper earlier than your customized view class variable. Open your storyboard utilizing IB, then drag & drop a brand new UIView component to your controller and join the customized view outlet. It ought to work like magic. 💫


I promised retailers and actions within the heading of this part, so let’s speak a bit of bit about IBActions. They work precisely the identical as you’d anticipate them with controllers. You may merely hook-up a button to your customized view and delegate the motion to the customized view class. If you wish to ahead touches or particular actions to a controller, it is best to use the delegate pattern or go along with a easy block. 😎

Possession and container views

It’s potential to go away out all of the xib loading mechanism from the view occasion. We are able to create a set of extensions with a view to have a pleasant view loader with a customized view class from a xib file. This manner you do not want a container view anymore, additionally the proprietor of the file may be neglected from the sport, it is kind of the identical technique as reusable cells for tables and collections created by Apple. 🍎

You must know that going this fashion you may’t use your default UIView init strategies programmatically anymore, as a result of the xib file will deal with the init course of. Additionally in case you are making an attempt to make use of this type of customized views from a storyboard or xib file, you will not be capable of use your retailers, as a result of the correspondig xib of the view class will not be loaded. In any other case in case you are making an attempt to load it manyally you will run into an infinite loop and finally your app will crash like hell. 😈


import UIKit

extension UINib 
    func instantiate() -> Any? 
        return self.instantiate(withOwner: nil, choices: nil).first
    


extension UIView 

    static var nib: UINib 
        return UINib(nibName: String(describing: self), bundle: nil)
    

    static func instantiate(autolayout: Bool = true) -> Self 
        
        func instantiateUsingNib<T: UIView>(autolayout: Bool) -> T 
            let view = self.nib.instantiate() as! T
            view.translatesAutoresizingMaskIntoConstraints = !autolayout
            return view
        
        return instantiateUsingNib(autolayout: autolayout)
    


class CustomView: UIView 

    @IBOutlet weak var textLabel: UILabel!




Similar to with desk or assortment view cells this time it’s a must to set your customized view class on the view object, as an alternative of the File’s Proprietor. It’s a must to join your retailers and mainly you are finished with all the pieces. 🤞


Any further it is best to ALWAYS use the instantiate technique in your customized view object. The excellent news is that the perform is generic, returns the correct occasion kind and it is extremely reusable. Oh, btw. I already talked about the unhealthy information… 🤪

There may be additionally yet one more approach by overriding awakeAfter, however I might not depend on that resolution anymore. In many of the instances you may merely set the File’s Proprietor to your customized view, and go along with a container, that is a protected wager. If in case you have particular wants you may want the second strategy, however please watch out with that. 😉



Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

The abstract Vapor service factory design pattern

by learningcode_x1mckf
February 1, 2023
0
The abstract Vapor service factory design pattern

I've written a number of articles about manufacturing unit design patterns on my weblog and this time I might like to speak a couple of particular one, which...

Read more

SwiftNIO tutorial – The echo server

by learningcode_x1mckf
January 27, 2023
0
SwiftNIO tutorial – The echo server

Intoducing SwiftNIO In the event you used a excessive degree net framework, corresponding to Vapor, up to now, you would possibly had some interplay with occasion loops...

Read more

Introducing – Vapor cheatsheet – The.Swift.Dev.

by learningcode_x1mckf
January 23, 2023
0
Introducing – Vapor cheatsheet – The.Swift.Dev.

Out there on Gumroad Thanks for supporting my work by buying the cheatsheet. 🙏 Download now A whole Vapor framework reference for novices. greater than...

Read more

iCloud Programming Tutorial for iOS: An Introduction

by learningcode_x1mckf
January 18, 2023
0
iCloud Programming Tutorial for iOS: An Introduction

Editor’s observe: This week, we work with Ziad Tamim once more to provide you an introduction of iCloud programming. You’ll learn to save and retrieve knowledge from iCloud.On...

Read more

Easy multipart file upload for Swift

by learningcode_x1mckf
January 18, 2023
0
Easy multipart file upload for Swift

I imagine that you've got already heard in regards to the well-known multipart-data add method that everybody likes to add recordsdata and submit type knowledge, but when not,...

Read more
Next Post
How to Determine Which Element Has Focus in JavaScript

How JavaScript Works Behind the Scenes

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Code coverage for Swift Package Manager based apps

Code coverage for Swift Package Manager based apps

September 25, 2022
How to Use localStorage in JavaScript

How to Use localStorage in JavaScript

September 18, 2022
Build Enumerations of Constants With Python’s Enum – Real Python

Build Enumerations of Constants With Python’s Enum – Real Python

October 3, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • Java :Full Stack Developer – Western Cape saon_careerjunctionza_state
  • Pay What You Want for this Learn to Code JavaScript Certification Bundle
  • UPB Java Jam brings coffeehouse vibes to Taylor Down Under | Culture

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?