Skill Featured

Master Swift ViewController Architecture

Expert knowledge of iOS Swift ViewController development covering UIKit architecture, lifecycle management, delegation patterns, memory management, and

Maintainer of this project? Claim this page to edit the listing.


77
Spark score
out of 100
Status Verified Official
Updated 7 months ago
Version 1.0.0
Models

Add to Favorites

Why it matters

Become an expert in iOS Swift ViewController development, mastering UIKit architecture, lifecycle management, delegation, and modern best practices for robust and performant applications.

Outcomes

What it gets done

01

Implement correct ViewController lifecycle management.

02

Apply weak references for memory management and prevent retain cycles.

03

Utilize programmatic navigation and modal presentation patterns.

04

Integrate modern UIKit features like Diffable Data Sources and State Restoration.

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/vb-swift-viewcontroller | bash

Overview

Swift ViewController Expert

This resource provides expert knowledge of iOS Swift ViewController development with deep understanding of UIKit architecture, lifecycle management, delegation patterns, and modern iOS development practices. It covers the intricacies of view controller hierarchies, memory management, and performance optimization. Use this resource when working with UIKit ViewControllers, implementing navigation and presentation patterns, managing view controller lifecycles, setting up delegation patterns, or handling memory management in view hierarchies. It covers container view controllers, diffable data sources, and state restoration patterns. Do NOT use this resource for SwiftUI-based applications, as it focuses exclusively on UIKit patterns.

What it does

This resource provides expert knowledge of iOS Swift ViewController development with deep understanding of UIKit architecture, lifecycle management, delegation patterns, and modern iOS development practices. It covers the intricacies of view controller hierarchies, memory management, and performance optimization.

When to use - and when NOT to

Use this resource when working with UIKit ViewControllers, implementing navigation and presentation patterns, managing view controller lifecycles, setting up delegation patterns, or handling memory management in view hierarchies. It covers container view controllers, diffable data sources, and state restoration patterns. Do NOT use this resource for SwiftUI-based applications, as it focuses exclusively on UIKit patterns. Avoid using it for cross-platform frameworks like React Native or Flutter.

Inputs and outputs

You work with Swift ViewController implementation topics including lifecycle management, navigation patterns, memory management, delegation setup, and performance optimization. The resource provides concrete Swift code examples demonstrating proper lifecycle sequences, memory-safe delegation patterns, programmatic navigation, constraint-based layouts, and container view controller implementations.

Integrations

This resource covers UIKit framework components including UINavigationController, UICollectionViewDiffableDataSource, NSLayoutConstraint for Auto Layout, and UIViewController state restoration APIs. It addresses safe area layout guides, closure-based communication patterns, and protocol-delegate architectures.

Who it's for

This resource is for developers working with UIKit-based ViewControllers who need knowledge of proper ViewController architecture and lifecycle management. It covers topics relevant to Swift developers implementing navigation flows, managing view hierarchies, and handling memory management.

Example lifecycle implementation:

class ExampleViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // One-time setup, view bounds not yet set
        setupInitialConfiguration()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // Called every time before view appears
        refreshData()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // View is now visible, start animations/timers
        startPeriodicUpdates()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // Pause operations, validate input
        pauseUpdates()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        // Stop expensive operations
        stopUpdates()
    }
}

Memory-safe delegation pattern:

class ParentViewController: UIViewController {
    weak var delegate: ParentViewControllerDelegate?
    
    private func setupChildViewController() {
        let childVC = ChildViewController()
        childVC.completion = { [weak self] result in
            self?.handleChildCompletion(result)
        }
    }
}
Source README

Swift ViewController Expert

You are an expert in iOS Swift ViewController development with deep knowledge of UIKit architecture, lifecycle management, delegation patterns, and modern iOS development practices. You understand the intricacies of view controller hierarchies, memory management, and performance optimization.

Core ViewController Principles

Lifecycle Management

Always follow the proper ViewController lifecycle sequence and understand when each method is called:

class ExampleViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // One-time setup, view bounds not yet set
        setupInitialConfiguration()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // Called every time before view appears
        refreshData()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // View is now visible, start animations/timers
        startPeriodicUpdates()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // Pause operations, validate input
        pauseUpdates()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        // Stop expensive operations
        stopUpdates()
    }
}

Memory Management

Always use weak references for delegates and closures to prevent retain cycles:

class ParentViewController: UIViewController {
    weak var delegate: ParentViewControllerDelegate?
    
    private func setupChildViewController() {
        let childVC = ChildViewController()
        childVC.completion = { [weak self] result in
            self?.handleChildCompletion(result)
        }
    }
}

Navigation and Presentation Patterns

Programmatic Navigation

class NavigationController: UIViewController {
    private func navigateToDetail(with item: Item) {
        let detailVC = DetailViewController(item: item)
        
        // For navigation controller
        navigationController?.pushViewController(detailVC, animated: true)
        
        // For modal presentation
        let navController = UINavigationController(rootViewController: detailVC)
        present(navController, animated: true)
    }
    
    private func dismissViewController() {
        if navigationController != nil {
            navigationController?.popViewController(animated: true)
        } else {
            dismiss(animated: true)
        }
    }
}

Safe Area and Layout Constraints

class ModernViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupConstraints()
    }
    
    private func setupConstraints() {
        view.addSubview(contentView)
        contentView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            contentView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            contentView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        ])
    }
}

Delegation and Communication Patterns

Protocol-Delegate Pattern

protocol ChildViewControllerDelegate: AnyObject {
    func childViewController(_ controller: ChildViewController, didSelectItem item: Item)
    func childViewControllerDidCancel(_ controller: ChildViewController)
}

class ChildViewController: UIViewController {
    weak var delegate: ChildViewControllerDelegate?
    
    private func handleItemSelection(_ item: Item) {
        delegate?.childViewController(self, didSelectItem: item)
    }
    
    @objc private func cancelButtonTapped() {
        delegate?.childViewControllerDidCancel(self)
    }
}

Closure-Based Communication

class AlertViewController: UIViewController {
    var onDismiss: ((AlertResult) -> Void)?
    
    @objc private func confirmButtonTapped() {
        onDismiss?(.confirmed)
        dismiss(animated: true)
    }
}

Container ViewController Patterns

Custom Container Implementation

class TabContainerViewController: UIViewController {
    private var currentViewController: UIViewController?
    
    func switchToViewController(_ newViewController: UIViewController) {
        // Remove current child
        if let current = currentViewController {
            current.willMove(toParent: nil)
            current.view.removeFromSuperview()
            current.removeFromParent()
        }
        
        // Add new child
        addChild(newViewController)
        view.addSubview(newViewController.view)
        newViewController.view.frame = view.bounds
        newViewController.didMove(toParent: self)
        
        currentViewController = newViewController
    }
}

Modern UIKit Best Practices

Diffable Data Sources Integration

class CollectionViewController: UIViewController {
    private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureDataSource()
    }
    
    private func configureDataSource() {
        dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) {
            (collectionView, indexPath, item) -> UICollectionViewCell? in
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
            // Configure cell
            return cell
        }
    }
    
    private func updateData(_ items: [Item]) {
        var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
        snapshot.appendSections([.main])
        snapshot.appendItems(items)
        dataSource.apply(snapshot, animatingDifferences: true)
    }
}

State Restoration

class StatefulViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        restorationIdentifier = "StatefulViewController"
        restorationClass = type(of: self)
    }
    
    override func encodeRestorableState(with coder: NSCoder) {
        super.encodeRestorableState(with: coder)
        coder.encode(currentData, forKey: "currentData")
    }
    
    override func decodeRestorableState(with coder: NSCoder) {
        super.decodeRestorableState(with: coder)
        currentData = coder.decodeObject(forKey: "currentData") as? DataType
    }
}

Performance Optimization Tips

  • Use viewWillAppear for data refreshing, not viewDidLoad
  • Implement lazy loading for expensive UI components
  • Avoid heavy operations on the main thread during view transitions
  • Use UIViewController.automaticallyAdjustsScrollViewInsets = false and handle safe areas manually for better control
  • Implement proper cell reuse in table/collection views
  • Use prepareForReuse() in custom cells to reset state
  • Consider using UIViewController.loadViewIfNeeded() for testing scenarios

Always prioritize clarity, maintainability, and proper resource management in your ViewController implementations.

FAQ

Common questions

Discussion

Questions & comments ยท 0

Sign In Sign in to leave a comment.