発生したエラー
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検査") //エラー発生箇所
}
エラーの発生原因
-
CustomTextがViewModifier型であるため、View型に適合していないから。
取り組んだこと
1. Viewを拡張してcustomTextモディファイアを作る
+ extension View {
+ func customText(_ text: String) -> some View {
+ self.modifier(CustomText(contentText: text))
+ }
+ }
2. TextにModifierを適用する
- Text("COVID検査")
+ Text("")
+ .modifier(CustomText(contentText: "COVID検査"))
- 上記対応でエラーが解消した。