0
0

【SwiftUI】高さ可変のTextEditor

Posted at

完成イメージ

  • 入力が空の場合はプレースホルダーを表示
  • 改行した分だけ高さが変化する

コード

swiftUI
import SwiftUI

struct DynamicHeightTextEditorView: View {
    // 入力するテキスト
    @Binding var text: String
    // プレースホルダーの文字
    let placeholder: String
    // 最大の高さ
    let maxHeight: CGFloat

    var body: some View {
        ZStack(alignment: .leading) {
            // テキストエディター
            HStack {
                if text.isEmpty {
                    Text(placeholder)
                        .foregroundColor(.gray)
                } else {
                    Text(text)
                }
                Spacer(minLength: 0)
            }
            .allowsHitTesting(false)
            .foregroundColor(.clear)
            .padding(.horizontal, 5)
            .padding(.vertical, 10)
            .background(
                TextEditor(text: $text)
                    .offset(y: 1.8)
            )
        }
        .padding(.horizontal, 10)
        .frame(maxHeight: maxHeight)
        .fixedSize(horizontal: false, vertical: true)
        .background(Color.white)
        .mask(RoundedRectangle(cornerRadius: 18).padding(.vertical, 3))
    }
}


#Preview {
    struct PreviewView: View {
        @State private var text: String = ""

        var body: some View {
            HStack {
                DynamicHeightTextEditorView(
                    text: $text,
                    placeholder: "入力してください。",
                    maxHeight: 200
                )
            }
            .padding()
            .background(Color.mainColor)
        }
    }
    return PreviewView()
}

参考資料

今回こちらの記事を参考にさせていただきました。textが空の時にプレースホルダーが表示されなかった点を修正しました。

【SwiftUI】チャットアプリのような動的な高さの TextEditor を実装する

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