• This repository has been archived on 06/Sep/2019
  • Stars
    star
    1,167
  • Rank 40,028 (Top 0.8 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Natalie - Storyboard Code Generator (for Swift)

Natalie

Natalie - Storyboard Code Generator (for Swift)

Swift

Current codebase is Swift 4 compatible.

Swift 3.x code may be found from swift3 branch

Swift 2.x code may be found from swift2 branch

Swift 1.x code may be found from swift2 branch

Synopsis

Natalie generates Swift code based on storyboard files to make work with Storyboards and segues easier. Generated file reduce usage of Strings as identifiers for Segues or Storyboards.

Proof of concept implementation to address the String issue for strongly typed Swift language. Natalie is a Swift command-line application (written in Swift) that produces a single .swift file with a bunch of extensions to project classes along the generated Storyboard enum.

Natalie is written in Swift and requires Swift to run. The project uses SWXMLHash as a dependency to parse XML and due to framework limitations.

Enumerate Storyboards

Generated enum Storyboards with a convenient interface (drop-in replacement for UIStoryboard).

struct Storyboards {
    struct Main {...}
    struct Second {...}
    ...

Instantiate initial view controller for storyboard

let vc = Storyboards.Main.instantiateInitialViewController()

Instantiate ScreenTwoViewController in storyboard, using storyboard id

let vc = Storyboards.Main.instantiateScreenTwoViewController()

example usage for prepareForSegue()

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  if segue == MainViewController.Segue.ScreenOneSegue {    
    let viewController = segue.destinationViewController as? MyViewController
    viewController?.view.backgroundColor = UIColor.yellowColor()
  }
}

...it could be switch { } statement, but it's broken.

Segues

Perform segue

self.perform(segue: MainViewController.Segue.ScreenOneSegue, sender: nil)

Each custom view controller is extended with this code and provide a list of available segues and additional information from Storyboard.

Segue enumeration contains list of available segues

kind property represent types Segue

destination property return type of destination view controller.

extension MainViewController {

    enum Segue: String, Printable, SegueProtocol {
        case ScreenOneSegueButton = "Screen One Segue Button"
        case ScreenOneSegue = "ScreenOneSegue"

        var kind: SegueKind? {
            ...
        }

        var destination: UIViewController.Type? {
            switch (self) {
            case ScreenOneSegueButton:
                return ScreenOneViewController.self
            case ScreenOneSegue:
                return ScreenOneViewController.self
            default:
                assertionFailure("Unknown destination")
                return nil
            }
        }

        var identifier: String { return self.description }
        var description: String { return self.rawValue }
    }
}

Reusable Views To Improve Performance

Collections and tables views use reuseidentifier on cell to recycle a view.

If you define it, their custom view controllers will be extended with a Reusable enumeration, which contains list of available reusable identifiers

example to dequeue a view with Reusable enumeration with UITableView:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(ScreenTwoViewController.Reusable.MyCell, forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = "\(indexPath.row)"
    return cell
}

Before dequeuing your view, you must register a class or a xib for each identifier. If your cell view has custom class defined in storyboard, in your controller you can call directly

override func viewDidLoad()  {
    tableView.registerReusableCell(MainViewController.Reusable.MyCell)
}

You can pass the view instead - the view must define the reuseidentifier

    tableView.registerReusableCell(tableViewCell)

If your reusable custom view, you can also execute code according to reusable values

class MyCustomTableViewCell: UITableViewCell {
    override func prepareForReuse() {
        if self == MyCustomTableViewController.Reusable.MyCell {
            ...
        }
        else if self == MyCustomTableViewController.Reusable.mySecondCellId {
            ...
        }
    }
}

Colors (iOS 11, macOS 10.13)

Generate an UIColor (or NSColor) static property for each asset colors used in your storyboard.

Installation

Swift Package Manager

$ git clone https://github.com/krzyzanowskim/Natalie.git
$ cd Natalie
$ ./scripts/build.sh
$ Binary at path ./Natalie/natalie

if you want easy Xcode integration you may want to install the binary to be easily accessible for any application from /usr/local/bin

$ cp natalie /usr/local/bin

Homebrew

$ brew install natalie

You can also put natalie executable file at the root of your project folder and keep it under version control. This way everyone even your CI will be able to generate the files.

Xcode Integration

Natalie can be integrated with Xcode in such a way that the Storyboards.swift the file will be updated with every build of the project, so you don't have to do it manually every time.

This is my setup created with New Run Script Phase on Build Phase Xcode target setting. It is important to move this phase above Compilation phase because this file is expected to be up to date for the rest of the application.

  • Select the project in the Project Navigator on the left of your Xcode window
  • Select your App Target in the list
  • Go in the "Build Phases" tab
  • Click on the "+" button on the upper left corner and choose "New Run Script Phase" and copy/paste script:
# Adjust path to "natalie" binary
# NATALIE_PATH="$PROJECT_DIR/natalie"
NATALIE_PATH="/usr/local/bin/natalie"

if [ -f $NATALIE_PATH ]; then
    echo "Natalie Generator: Determining if generated Swift file is up-to-date."
    
    BASE_PATH="$PROJECT_DIR/$PROJECT_NAME"
    OUTPUT_PATH="$BASE_PATH/Storyboards.swift"

    if [ ! -e "$OUTPUT_PATH" ] || [ -n "$(find "$BASE_PATH" -type f -name "*.storyboard" -newer "$OUTPUT_PATH" -print -quit)" ]; then
        echo "Natalie Generator: Generated Swift is out-of-date; re-generating..."

        /usr/bin/chflags nouchg "$OUTPUT_PATH"
        "$NATALIE_PATH" "$BASE_PATH" > "$OUTPUT_PATH"
        /usr/bin/chflags uchg "$OUTPUT_PATH"

        echo "Natalie Generator: Done."
    else
        echo "Natalie Generator: Generated Swift is up-to-date; skipping re-generation."
    fi
else 
    echo "error: Could not find Natalie Generator at $NATALIE_PATH; Please visit https://github.com/krzyzanowskim/Natalie for installation instructions."
    exit 1
fi
  • add Storyboards.swift to the project.

Usage:

Download Natalie from Github: https://github.com/krzyzanowskim/Natalie and use it in the console, for example like this:

$ git clone https://github.com/krzyzanowskim/Natalie.git
$ cd Natalie

The command expects one of two types of parameters:

  • path to a single .storyboard file
  • path to a folder

If the parameter is a Storyboard file, then this file will be used. If a path to a folder is provided Natalie will generate code for every storyboard found inside.

$ natalie NatalieExample/NatalieExample/Base.lproj/Main.storyboard > NatalieExample/NatalieExample/Storyboards.swift

Contribution

Please submit Pull Request against current development branch.

Author and contact

Marcin Krzyżanowski

Licence

The MIT License (MIT)

Copyright (c) 2015 Marcin Krzyzanowski

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

CryptoSwift

CryptoSwift is a growing collection of standard and secure cryptographic algorithms implemented in Swift
Swift
10,176
star
2

STTextView

Performant and reusable text view component (TextKit 2), with line numbers and more. UITextView / NSTextView replacement.
Swift
1,073
star
3

OpenSSL

OpenSSL package for SwiftPM, CocoaPod, and Carthage, multiplatform
C
919
star
4

ObjectivePGP

ObjectivePGP is an open-source library for iOS and macOS that provides developers with tools for implementing OpenPGP encryption and decryption, digital signing, and signature verification in their applications, thereby enhancing security and data integrity.
Objective-C
667
star
5

OnlineSwiftPlayground

Online Swift Playground
Swift
245
star
6

CoreTextSwift

CoreText Swift bindings
Swift
158
star
7

NSTableView-Sections

NSTableView with sections (similar to UITableView)
Swift
89
star
8

SwiftUI.TextEdit

SwiftUI proof-of-concept text edit component
Swift
87
star
9

JSONCodable

JSON Codable is what we need 90% of the time
Swift
75
star
10

unnetpgp

*Deprecated* NetPGP wrapper. Use ObjectivePGP
C
67
star
11

reorder

Reorder Swift functions
Swift
57
star
12

SwiftUI.AnimatedImage

SwiftUI AnimatedImage View
Swift
56
star
13

SwiftUI.SplitView

Swift
48
star
14

RepetitiveTask

Swift
40
star
15

tree-sitter-xcframework

binary build of tree-sitter for apple platforms
C
37
star
16

BoyerMoore

Boyer-Moore algorithm sample
Swift
37
star
17

GeneratedResults-UITableView

Practical Swift: pages generator - build once, use many
Swift
36
star
18

STTextView-Plugin-Neon

Source Code Syntax Highlighting
C
33
star
19

STTextKitPlus

Collection of TextKit 2 helpers used to build STTextView.
Swift
28
star
20

MKDataScanner

NSScanner for NSData and files.
Objective-C
16
star
21

antlr-swift-playground

Antlr Swift Parser playground
Swift
14
star
22

CollectionSafeIndex

Get the element at the specified index only if it is within bounds, otherwise nil
Swift
11
star
23

CoreTextWorkshop

Take a look at the CoreText API - a foundation of layout and drawing text on macOS and iOS. In this workshop we’ll attempt to build Text Label (akin UILabel), learn about layers of CoreText API and how to use it.
Swift
10
star
24

AES256CBC

Most convenient AES256-CBC encryption for Swift 2 & 3
Swift
8
star
25

OpenSSL-Package

OpenSSL package for SwiftPM
Swift
8
star
26

RawData

Swift RawData CollectionType
Swift
7
star
27

STTextView-Plugin-Annotations

Annotations Plugin
Swift
7
star
28

STTextView-Plugin-Template

Template Plugin repository for STTextView
Swift
7
star
29

CodeEditView

custom text view implementation
Swift
6
star
30

Kitura-Session-Kuery

Kitura-Session store using Swift-Kuery (SQL database abstraction layer) as the backing store
Swift
6
star
31

CloudKitWebServices

CloudKit Web Services framework for everyone else...
6
star
32

TouchImageView

iOS UIImageView with convenient touch delegate
Objective-C
6
star
33

language-server-protocol

Language Server Protocol
Swift
6
star
34

sendable.wtf

HTML
5
star
35

Google1Password

1Password integration for Google sign-in view.
Objective-C
5
star
36

ChorusBirdie

Birdie singing songs game. SwiftCrunch hackathon project. Created over few hours from zero.
Swift
3
star
37

monaco-editor-vue-component

MonacoEditor component for Vue.js
Vue
2
star
38

AppleRadar-FileProviderEnumeratorNotificationSample

NSFileProviderManager.signalEnumerator does not trigger update of UIDocumentBrowserViewController
Swift
2
star
39

GNUGadu

GNU Gadu is instant messaging client designed to work with protocols common in Poland (but not only). Contrary to its name, is not part of the GNU project.
C
2
star
40

MKScrollView

Alternative to UIScrollView. Proof of concept implementation.
Objective-C
1
star