LoginSignup
1
3

More than 1 year has passed since last update.

【SwiftUI】TextEditorにプレイスホルダーを付けたい

Posted at

はじめに

複数行の文字入力をさせたい時に登場するのがTextEditorです。
(iOS16からはTextFieldでもできるようになった)
しかし、TextEditorにはプレイスホルダーがつけられません。
プレイスホルダーがないと何をする場所なのかユーザーはわかりにくいと思います。

TextEditorにプレイスホルダーを付けなければいけないことがあったので、その時の解決方法を記録しておきます。

こんな感じ

Simulator Screen Recording - iPhone 14 - 2023-02-12 at 20.20.20.gif

実装

TextEditorView
import SwiftUI

struct TextEditorView: View {

    private let placeholder: String

    @Binding private var text: String

    init(_ placeholder: String, text: Binding<String>) {
        self.placeholder = placeholder
        self._text = text
    }

    var body: some View {
        ZStack(alignment: .topLeading) {
            TextEditor(text: $text)
            Text("ここにテキストを入力してください")
                .opacity(text.isEmpty ? 0.3 : 0.0)
                .padding(.init(top: 9, leading: 8, bottom: 0, trailing: 0))
                .allowsHitTesting(false)
        }
    }
}

使い方

ContentView
import SwiftUI

struct ContentView: View {
    @State var text: String = ""
    var body: some View {
        TextEditorView("ここに文字を入力してください", text: $text)
    }
}

おわり

標準機能として提供してくれると嬉しいです。

1
3
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
3