A Powerful , Extensible CSS Parser written in pure Swift.

Related tags

UI SwiftCssParser
Overview


A Powerful , Extensible CSS Parser written in pure Swift.

Basic Usage

From CSS:

#View {
 "width" : 118;
 "height" : 120.5;
 "color1" : "#888888";
 "color2" : RGB(200,200,200);
 "color3" : RGB(200,200,200,0.5);
 "font1" : "Helvetica-Bold" 18;
 "font2" : "Cochin";
 "size" : 10 10;
 }

To Cocoa:

let width = css.int(selector: "#View", key: "width") // Int
let height = css.double(selector: "#View", key: "height") //Double
let color1 = css.color(selector: "#View", key: "color1") //UIColor
let font1  = css.font(selector: "#View", key: "font1") //UIFont
let font2 = css.font(selector: "#View", key: "font2", fontSize: 14) //UIFont
let size = testSwiftCSS.size(selector: "#View", key: "size") //CGsize

It's very easy to setup and parse CSS with SwiftCssParser:

//1.Get CSS file path
let path = Bundle.main.url(forResource: "cssFileNmae", withExtension: "css")
//2.Get parsed CSS
let css = SwiftCSS(CssFileURL: path)
//3.Use it
let width = css.int(selector: "#View", key: "width")

Extension

It's very easy to build your own Powerful, Flexiable CSS based solutions base on SwiftCssParser.

Example1: SwiftDeviceCss

​ In most cases, Auto Layout can help us calculates the size and location of our views. But in some cases, we need to set specifc size and location for our views based on device type (device's screen size) to accomplish the Pixel Perfect design.

​ So, we can use SwiftCssParser to get layout value from CSS file. Different Device has different configuration file.

public let SwiftDeviceCss = SwiftCssStyleSheet.deviceCss()

class SwiftCssStyleSheet {
    
    private enum ScreenSize {
        case _320_480 //iPhone4 etc.
        case _320_568 //iPhone5 etc.
        //iPhone6....
    }
    
    static private let screenSize: ScreenSize = {
        let screen = UIScreen.main
        let size = UIScreen.main.fixedCoordinateSpace.bounds.size
        switch (size.width,size.height) {
        case (320,640):
        	return ._320_480
        //......
        }
    }()
    
    static func deviceCss() -> SwiftCSS {
        switch self.screenSize {
        case ._320_480:
            return SwiftCSS(CssFileURL: URL.CssURL(name: "iPhone4"))
        case ._320_568:
            return SwiftCSS(CssFileURL: URL.CssURL(name: "iPhone5"))
        //......
        }
    }
    
}

Then just layout:

view.frame.size = SwiftDeviceCss.size(selector: "#View", key: "size")

Exeample2: SwiftCssTheme

We can also create a powerful theme manager base on SwiftCssParser.

For example, we want to create a night & day theme.

public class SwiftCssTheme {
    
    public static let updateThemeNotification = Notification.Name("SwiftCSSThemeUpdate")
    
    public enum Theme {
        case day
        case night
    }
    
    public static var theme: Theme = .day {
        didSet {
            switch theme {
            case .day:
                self.themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "day"))
            case .night:
                self.themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "night"))
            }
            NotificationCenter.default.post(name: updateThemeNotification, object: nil)
        }
    }
    
    public static var themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "day"))
}

If we want to be able to dynamically modify the background color of UIView:

extension UIView {
    
    private struct AssociatedKeys {
        static var selector = "themeColorSelector"
        static var key = "themeColorKey"
    }
    
    var backgroundColorCSS: (selector: String,key: String) {
        get {
        	let selector = //Use objc_getAssociatedObject to get value.....
        	let key = //.....
            return (selector,key)
        }
        
        set {
            let selector = newValue.selector
            let key = newValue.key
            
            //Use objc_setAssociatedObject to set value......   
            
            NotificationCenter.default.addObserver(self, selector: #selector(_cssUpdateBackgroundColor), name: SwiftCssTheme.updateThemeNotification, object: nil)
            
            _cssUpdateBackgroundColor()
        }
    }
    
    private dynamic func _cssUpdateBackgroundColor() {
        self.backgroundColor = SwiftCssTheme.themeCSS.color(selector: self.backgroundColorCSS.selector, key: self.backgroundColorCSS.key)
    }
}

Then, we just need to specify the background color's CSS selector and key:

self.view.backgroundColorCSS = ("#View","color")

Changing theme is even easier:

@IBAction func changeColor(_ sender: UIButton) {
    if SwiftCssTheme.theme == .day {
        SwiftCssTheme.theme = .night
    } else {
        SwiftCssTheme.theme = .day
    }
}

All the code and demo can be found in the project. Feel free to download and experiment. Advice and pull requests are welcome.

Installation

CocoaPods:

pod 'SwiftCssParser'

License

SwiftCssParser is under the MIT license.

You might also like...
Material design components for iOS written in Swift
Material design components for iOS written in Swift

MaterialKit NOTE: This project is unmaintained. Material design components (inspired by Google Material Design) for iOS written in Swift Please feel f

Highly customizable Action Sheet Controller with Assets Preview written in Swift
Highly customizable Action Sheet Controller with Assets Preview written in Swift

PPAssetsActionController Play with me ▢️ πŸ– If you want to play with me, just tap here and enjoy! 🎩 πŸ•΄ Show me πŸŽͺ Try me πŸ“² The easiest way to try me

Simple PhotoBrowser/Viewer inspired by facebook, twitter photo browsers written by swift
Simple PhotoBrowser/Viewer inspired by facebook, twitter photo browsers written by swift

SKPhotoBrowser Simple PhotoBrowser/Viewer inspired by facebook, twitter photo browsers written by swift features Display one or more images by providi

πŸ” Awesome fully customize search view like Pinterest written in Swift 5.0 + Realm support!
πŸ” Awesome fully customize search view like Pinterest written in Swift 5.0 + Realm support!

YNSearch + Realm Support Updates See CHANGELOG for details Intoduction πŸ” Awesome search view, written in Swift 5.0, appears search view like Pinteres

An easy to use FAQ view for iOS written in Swift
An easy to use FAQ view for iOS written in Swift

FAQView An easy to use FAQ view for iOS written in Swift. This view is a subclass of UIView. Setup with CocoaPods If you are using CocoaPods add this

TSnackBarView is a simple and flexible UI component fully written in Swift
TSnackBarView is a simple and flexible UI component fully written in Swift

TSnackBarView is a simple and flexible UI component fully written in Swift. TSnackBarView helps you to show snackbar easily with 3 styles: normal, successful and error

TDetailBoxView is a simple and flexible UI component fully written in Swift
TDetailBoxView is a simple and flexible UI component fully written in Swift

TDetailBoxView is a simple and flexible UI component fully written in Swift. TDetailBoxView is developed to help users quickly display the detail screen without having to develop from scratch.

TSwitchLabel is a simple and flexible UI component fully written in Swift.
TSwitchLabel is a simple and flexible UI component fully written in Swift.

TSwitchLabel is a simple and flexible UI component fully written in Swift. TSwitchLabel is developed for you to easily use when you need to design a UI with Label and Switch in the fastest way without having to spend time on develop from scratch.

🏞 A simple iOS photo and video browser with optional grid view, captions and selections written in Swift5.0
🏞 A simple iOS photo and video browser with optional grid view, captions and selections written in Swift5.0

Introduction 🏞 MediaBrowser can display one or more images or videos by providing either UIImage objects, PHAsset objects, or URLs to library assets,

Comments
  • Make a framework?

    Make a framework?

    Hi, Will you later package it as frameworks usable with SPM, carthage and cocoapod ie. separate demo application code on file system like you do in xcode using group, ...

    opened by phimage 1
  • CssLexer.Token enum doesn't contain URL type

    CssLexer.Token enum doesn't contain URL type

    Wanted to parse background-image atribute which should contain URL in some cases https://developer.mozilla.org/en-US/docs/Web/CSS/url() https://www.w3schools.com/cssref/pr_background-image.asp

    but it is not present

    opened by kyzmitch 0
  • Can't add over CocoaPods

    Can't add over CocoaPods

    Hi,

    I wanted to use your framework, but it seems usual pod install doesn't work and even pod repo update didn't help. Also tried to add new source of podspec to Podfile like: source 'https://github.com/100mango/SwiftCssParser.git'

    and after that it is different error:

    [!] An unexpected version directory `Assets.xcassets` was encountered for the `/Users/homedir/.cocoapods/repos/100mango/SwiftCssParser` Pod in the `SwiftCssParser` repository.
    
    opened by kyzmitch 1
Releases(0.1.0)
Owner
null
πŸš€ Elegant Pager View fully written in pure SwiftUI.

PagerTabStripView Made with ❀️ by Xmartlabs team. XLPagerTabStrip for SwiftUI! Introduction PagerTabStripView is the first pager view built in pure Sw

xmartlabs 482 Jan 9, 2023
Powerful and easy-to-use vector graphics Swift library with SVG support

Macaw Powerful and easy-to-use vector graphics Swift library with SVG support We are a development agency building phenomenal apps. What is Macaw? Mac

Exyte 5.9k Jan 1, 2023
Stencil is a simple and powerful template language for Swift.

Stencil Stencil is a simple and powerful template language for Swift. It provides a syntax similar to Django and Mustache. If you're familiar with the

Stencil Project 2.2k Jan 4, 2023
Swipe Left2Right & Right2Left, pure SwiftUI implementation

SwipeCell Preview Features Swipe cell from Left2Right & Right2Left. Destructive swipe Usage Simply add onSwipe(leading, trailing) method to your list

Enes Karaosman 266 Jan 6, 2023
React.js like Mixin. More powerful Protocol-Oriented Programming.

Mixin ?? Why? Swift is Protocol-Oriented Programming, and it's more powerful by default implementations of extensions of protocols. You can mixin meth

Wan-Huang Yang 45 Dec 28, 2021
A message bar for iOS written in Swift.

Dodo, a message bar for iOS / Swift This is a UI widget for showing text messages in iOS apps. It is useful for showing short messages to the user, so

Evgenii Neumerzhitckii 874 Dec 13, 2022
Cool Animated music indicator view written in Swift

Cool Animated music indicator view written in Swift. ESTMusicIndicator is an implementation of NAKPlaybackIndicatorView in Swift for iOS 8. ζœ¬δΊΊθ‘—δ½œηš„δΉ¦η±γ€ŠLa

Aufree 465 Nov 28, 2022
An easy to use FAQ view for iOS written in Swift

FAQView An easy to use FAQ view for iOS written in Swift. This view is a subclass of UIView. Setup with CocoaPods If you are using CocoaPods add this

Mukesh Thawani 467 Dec 5, 2022
Whole, half or floating point ratings control written in Swift

FloatRatingView A simple rating view for iOS written in Swift! Supports whole, half or floating point values. I couldn't find anything that easily set

Glen Yi 546 Dec 8, 2022
A UITextView subclass that adds support for multiline placeholder written in Swift.

KMPlaceholderTextView A UITextView subclass that adds support for multiline placeholder written in Swift. Usage You can set the value of the placehold

Zhouqi Mo 794 Jan 7, 2023