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:
- Open your XCode and select: File > New > Package to create the swift package. In this case, we named it “MyLibrary”.
- 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.
- 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:
- In source control navigator, click right in the Remote option and select New “MyLibrary” Remote.
- Choose your account and then click create.
-
Commit and push these changes
-
Then, you can see the library in your repository
Install Library:
- To install the library you need to copy the url repository:
- In the external project go to the part to add packages
- Copy the url in the search bar, press enter and then click in add package
- Make sure that the library is in Frameworks, Libraries and Embedded Content
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
Source code of Library:
For a review the source code, please checkout my git repository git repository of this tutorial.