1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Qiita全国学生対抗戦Advent Calendar 2023

Day 25

【SwiftUI】Qiitaのマークダウンで使えるnoteがかっこよかったので作ってみた

Last updated at Posted at 2023-12-26

はじめに

Qiitaのマークダウンで作れる↓を作ってみることにしました。

あいうえお
かきくけこ

あいうえお
かきくけこ

あいうえお
かきくけこ

これかなりかっこいいですよね

サンプルアプリ

こんな感じのが作れます。
スクリーンショット 2023-12-27 21.20.47.png

実装

import SwiftUI

enum QiitaNoteType {
    case info
    case warn
    case alert
}

extension QiitaNoteType {
    var systemName: String {
        switch self {
        case .info:
            return "checkmark.circle.fill"
        case .warn:
            return "exclamationmark.circle.fill"
        case .alert:
            return "xmark.circle.fill"
        }
    }
    
    var foregroundStyle: Color {
        switch self {
        case .info:
            return .green
        case .warn:
            return .yellow
        case .alert:
            return .red
        }
    }
}

extension Label where Title == Text, Icon == EmptyView {
    init<T: StringProtocol>(_ title: T) {
        self.init(title: { Text(title) }, icon: EmptyView.init)
    }
}

struct QiitaNoteLabelStyle: LabelStyle {
    let qiitaNoteType: QiitaNoteType
    
    func makeBody(configuration: Configuration) -> some View {
        HStack(alignment: .top, spacing: 10) {
            Text(Image(systemName: qiitaNoteType.systemName))
                .foregroundStyle(qiitaNoteType.foregroundStyle)
                .baselineOffset(5)

            configuration.title
                .frame(maxWidth: .infinity, alignment: .leading)
        }
        .padding(15)
        .background(qiitaNoteType.foregroundStyle.opacity(0.1), in: .rect(cornerRadius: 10))
    }
}

extension LabelStyle where Self == QiitaNoteLabelStyle {
    static func qiitaNote(_ type: QiitaNoteType) -> QiitaNoteLabelStyle {
        .init(qiitaNoteType: type)
    }
}

使い方

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Label("あいうえお\nかきくけこ")
                .labelStyle(.qiitaNote(.info))
            
            Label("あいうえお\nかきくけこ")
                .labelStyle(.qiitaNote(.warn))
            
            Label("あいうえお\nかきくけこ")
                .labelStyle(.qiitaNote(.alert))
        }
        .padding(20)
    }
}

おわり

Labelを拡張して引数のiconを消してます。
iconはLabelStyleで追加してる感じですね

1
1
2

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?