Skip to content

Instantly share code, notes, and snippets.

@damodarnamala
Last active August 30, 2022 17:09
Show Gist options
  • Save damodarnamala/823dc3a5a9805d6db75d7f1d3c308af5 to your computer and use it in GitHub Desktop.
Save damodarnamala/823dc3a5a9805d6db75d7f1d3c308af5 to your computer and use it in GitHub Desktop.
SwiftUI styles like tailwind css
//
// ContentView.swift
// StylesApp
//
// Created by Damodar Namala on 30/08/22.
//
import SwiftUI
struct ContentView: View {
var body: some View {
Rectangle()
.apply("pl-100 fg-red radius-16 size-64")
}
}
extension View {
func apply(_ text : String) -> some View {
var leading: CGFloat = 0
var forgroundColor: Color = .black
var radius: CGFloat = 0
var toalSize: CGFloat = 0
let array = text.split(separator: " ")
if let leadingValue = array.first(where: { text in text.contains("pl") })!.components(separatedBy: "-").last,
let colorValue = array.first(where: { text in text.contains("fg") })!.components(separatedBy: "-").last,
let radiusValue = array.first(where: { text in text.contains("radius") })!.components(separatedBy: "-").last,
let sizeValue = array.first(where: { text in text.contains("size") })!.components(separatedBy: "-").last {
let leadingPoints = CGFloat(string: leadingValue)!
let radiusPoints = CGFloat(string: radiusValue)!
let sizePoints = CGFloat(string: sizeValue)!
let fgColor = colorValue == "red" ? Color.red : Color.blue
forgroundColor = fgColor
leading = leadingPoints
radius = radiusPoints
toalSize = sizePoints
}
return modifier(StyledView(leading: leading, color: forgroundColor, radius: radius, size: toalSize))
}
}
extension CGFloat {
init?(string: String) {
guard let number = NumberFormatter().number(from: string) else {
return nil
}
self.init(number.floatValue)
}
}
struct StyledView: ViewModifier {
let leading: CGFloat
let color: Color
let radius: CGFloat
let size: CGFloat
func body(content: Content) -> some View {
content
.frame(width: size, height: size, alignment: .center)
.cornerRadius(radius)
.padding(.leading, leading)
.foregroundColor(color)
.clipped()
}
}
@vikingosegundo
Copy link

.applay() should be .apply()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment