LoginSignup
0
2

【SwiftUI】カスタムのShapeStyleを作成する

Posted at

はじめに

私はデザインのことは分かりませんが、真っ黒や真っ白は目が疲れてしまって文字色には適していないという記事を見たことがありました。
私が見た記事は見つかりませんでしたが、同じようなことを書いてある記事はたくさんあります。

しかし、SwiftUIの標準で使用できるprimaryは真っ黒と真っ白です。
使うたびに分岐の処理を書くのは面倒です。
ですので、カスタムのShapeStyleを実装します。

サンプルアプリ

上が標準のprimaryで、
下がカスタムしたcustomPrimaryです。

ライトモード ダークモード
スクリーンショット 2024-01-03 19.49.08.png スクリーンショット 2024-01-03 19.50.48.png

実装

struct CustomPrimaryStyle: ShapeStyle {
    func resolve(in environment: EnvironmentValues) -> some ShapeStyle {
        switch environment.colorScheme {
        case .light:
            Color(red: 50 / 255, green: 50 / 255, blue: 50 / 255)
        case .dark:
            Color(red: 205 / 255, green: 205 / 255, blue: 205 / 255)
        @unknown default:
            fatalError()
        }
    }
}

extension ShapeStyle where Self == CustomPrimaryStyle {
    static var customPrimary: CustomPrimaryStyle {
        CustomPrimaryStyle()
    }
}

使い方

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("あいうえお")
                .foregroundStyle(.primary)
            Text("かきくけこ")
                .foregroundStyle(.primary)
            Text("さしすせそ")
                .foregroundStyle(.primary)
            Text("たちつてと")
                .foregroundStyle(.primary)
            
            Divider()
            
            Text("あいうえお")
                .foregroundStyle(.customPrimary)
            Text("かきくけこ")
                .foregroundStyle(.customPrimary)
            Text("さしすせそ")
                .foregroundStyle(.customPrimary)
            Text("たちつてと")
                .foregroundStyle(.customPrimary)
        }
        .fontWeight(.black)
    }
}

おわり

この実装をすることで普通のprimaryと同様の記述方法で書くことができます。

0
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
0
2