How to create UI System Library to iOS Projects vía Swift Packages

How to create UI System Library to iOS Projects vía Swift Packages

Introduction:

In big projects we need to modularize and define the design system as colors, typographies, iconography and more. To do that we can create a library to modularize existing iOS projects through Swift Packages, Cocoapods and similar ways.\

In this article we create and distribute a library in Swift Package and install and use that in an external project.

Requirements:

To understand this tutorial we need knowledge about:

  • Swift Packages
  • Decorator Design Pattern
  • Access Control in Swift

Create Library:

  1. Open your XCode and select: File > New > Package to create the swift package. In this case, we named it “MyLibrary”.
    alt text alt text
  2. In the Library we need to change the build mode to “Any iOS Device” and In the Package.swift file we need to change the platform and set the minimum version of iOS to support. alt text
  3. In our case we created the palette color vía decorator pattern. It is important to set public access control to the extension, to access from every project that uses this library
// MARK: - Color
public extension UIColor {
    convenience init(hex: UInt, alpha: CGFloat = 1) {
            self.init(
                red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
                green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
                blue: CGFloat(hex & 0x0000FF) / 255.0,
                alpha: alpha
            )
        }
    
    // MARK: - Blue
    static let blue100 = UIColor(hex: 0xd9e7fd)
    static let blue200 = UIColor(hex: 0xb4cffb)
    static let blue300 = UIColor(hex: 0x8eb7f9)
    static let blue400 = UIColor(hex: 0x699ff7)
}

Distribute Library:

  1. In source control navigator, click right in the Remote option and select New “MyLibrary” Remote.

alt text

  1. Choose your account and then click create.

alt text

  1. Commit and push these changes

  2. Then, you can see the library in your repository

alt text

Install Library:

  1. To install the library you need to copy the url repository:

alt text

  1. In the external project go to the part to add packages

alt text

  1. Copy the url in the search bar, press enter and then click in add package

alt text

  1. Make sure that the library is in Frameworks, Libraries and Embedded Content

alt text

Use Library:

In our Project we need to import the library and use the color palette like the image below:

import UIKit
import MyLibrary

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = .blue100
    }
    
}

And the result is as we expected

alt text

Source code of Library:

For a review the source code, please checkout my git repository git repository of this tutorial.

comments powered by Disqus