1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftでHTML,CSSを「Swiftらしく」書いてみよう

Posted at

はじめに

Swiftが好きな友人から「Swiftでwebを作っているんだけど…」という話をされました。
みんな一回は通る道だと思います。

swift htmlで調べてみると、いくつかSPMが見つかります。これとか。

しかし、上記パッケージだとCSSの書き方が全然Swiftらしくないんですよ。

他にもIgniteなどがありますが、こっちはCSSじゃなくてSwiftUIのmodifierでスタイルを作っている。これはこれでなんか違うんですよね、そのまんまSwiftでSwiftらしく書きたい、というのがこっちの要望です。

そこで、HTMLとCSSを、プロパティの名前はそのまま、Swiftらしく書けるパッケージを作ってみました。

Swift-HTML-CSS

HTMLは以下のように、SwiftUIらしく書くことができます。(いったん、HTMLへの変換をメインに考えているので、some View にはしませんでした。)

let document = HTML(styles: [myStyles]) {
    head {
        meta(charset: "UTF-8")
        meta(name: "viewport", content: "width=device-width, initial-scale=1.0")
        title("SwiftHTMLCSS Example")
    }

    body {
        div(className: "container") {
            h1(className: "name") {
                Text("Welcome to SwiftHTMLCSS")
            }

            h2 {
                Text("A Swift DSL for HTML & CSS")
            }

            p {
                Text("This is an example of writing HTML and CSS in a SwiftUI-like style.")
            }

            div {
                h3 {
                    Text("Features")
                }

                ul {
                    li {
                        Text("Type-safe HTML generation")
                    }
                    li {
                        Text("SwiftUI-like syntax")
                    }
                    li {
                        Text("CSS styling with enums")
                    }
                }
            }
        }
    }
}

let html = document.render()

また、課題となるCSSは、以下のようにPropertyの配列でかけるようにしてみました。

let myStyles: [Style] = [
    .rule(.tag("h1"), .tag("h2")) {
        textAlign(.center)
        color(hex: "#333")
        fontFamily("Arial", "sans-serif")
    },

    .rule(.className("name")) {
        color(hex: "#0066cc")
        fontSize(px: 24)
        fontWeight(.bold)
    },

    .rule(.tag("p")) {
        fontSize(px: 16)
        lineHeight(value: 1.6)
        margin(px: 10)
    },

    .rule(.className("container")) {
        width(percent: 80)
        margin(0, .auto)
        padding(px: 20)
    },

    .rule(.className("custom")) {
        maxWidth(px: 1200)
        minHeight(px: 400)
        opacity(value: 0.9)
    }
]

大分CSSそのものっぽい書き方ですが、swiftらしくもある書き方になったのではないでしょうか。

まとめ

今回のものは、iOSアプリに埋め込むとかそういうものではなく、純粋にswiftだけでHTML/CSSを書く、という欲求のもとに作成されたものです。実用的にさせるために色々考えてみます!

パッケージ作るのは楽しいのでみんなもやりましょう!

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?