Codementor Events

SwiftUI / UIKit Previews are the future of interface design

Published Oct 26, 2023
SwiftUI / UIKit Previews are the future of interface design

If you're still using IBDesignable, it's time to make the switch to Preview macro. Check out this quick video to learn why? Detail Video on Youtube click here to watch !

Introduction:
Why isn't SwiftUI's #Preview feature equivalent to UIKit's IBDesignable

Screenshot 2023-10-26 at 10.40.48 PM.png

I think many developers have encountered this situation during their development journey, and we have the #Preview feature in our toolkit to help us address it, whether we're working with Swift in UIKit or SwiftUI.

So how doest it work:  
Simply on your view controller write the below code

#Preview {
    let vc = ViewController()
    vc.loadViewIfNeeded()
    return vc
}

thats its and you will see a output , just like swiftUI preview

Screenshot 2023-10-26 at 10.43.43 PM.png

Full ViewController Code below

class ViewController: UIViewController {
    @IBOutlet weak var vlevelView: ProgressView!
    @IBOutlet weak var sStepper: UIStepper!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        vlevelView.borderWidth = 2
        sStepper.value = Double(vlevelView.value)
    }

    @IBAction func valueChanged(_ sender: UIStepper) {
        vlevelView.value = CGFloat(sender.value)
    }
    
}

#Preview {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateInitialViewController() as! ViewController
    vc.loadViewIfNeeded()
    vc.vlevelView.value = 0.2
    return vc
}

full project in the github link click here !

Happy Coding ✌️✌️

Discover and read more posts from Abdul Karim
get started