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

【SwiftUI】Static method 'buildExpression' requires that 'CustomText' conform to 'View'

Last updated at Posted at 2025-10-26

発生したエラー

Static method 'buildExpression' requires that 'CustomText' conform to 'View'

該当のコード

extension String {
    var isAlphanumeric: Bool {
        let range = "[a-zA-Z0-9]+"
        return NSPredicate(format: "SELF MATCHES %@", range).evaluate(with: self)
    }
}

struct CustomText: ViewModifier {
    let contentText: String
 
    func body(content: Content) -> some View {
        let array_text = Array(contentText).map{ String($0) }
        return HStack(spacing: 0) {
            ForEach(array_text, id: \.self) { item in
                if item.isAlphanumeric == true {
                    Text(item)
                        .font(.custom("Futura", size: 20))
                } else {
                    Text(item)
                        .font(.custom("HiraginoSans-W6", size: 20))
                }
            }
        }
    }
}

// 省略
var body: some View {
    CustomText(contentText: "COVID検査") //エラー発生箇所
}

エラーの発生原因

  • CustomTextViewModifier型であるため、View型に適合していないから。

取り組んだこと

1. Viewを拡張してcustomTextモディファイアを作る

+ extension View {
+     func customText(_ text: String) -> some View {
+        self.modifier(CustomText(contentText: text))
+    }
+ }

2. TextModifierを適用する

- Text("COVID検査")
+ Text("")
+    .modifier(CustomText(contentText: "COVID検査"))
  • 上記対応でエラーが解消した。
0
1
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
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?