0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Swift】TextEditorの@State textってユーザーが改行した位置も覚えてるの?

Posted at

結論

  • 覚えてました。
  • Textの中に明示的に示されていないですが、ユーザーの改行位置\nの位置も記録してくれるようです。

サンプルコード

このサンプルコードには生成AIを使用しています。

2画面構成の簡単なデモです。

  • 左画面が TextEditor(入力欄)、
  • 右画面が Text(出力表示欄)です。

ユーザーが改行を入れると、右側のプレビューにも同じ改行が反映されます。

import SwiftUI

struct ContentView: View {
    @State private var text: String = "ここに入力してください。\n改行を入れてみてください。"

    var body: some View {
        HStack {
            // 左画面:TextEditor(入力欄)
            VStack(alignment: .leading) {
                Text("📝 TextEditor")
                    .font(.headline)
                TextEditor(text: $text)
                    .padding()
                    .frame(minHeight: 200)
                    .border(Color.gray.opacity(0.4))
            }
            .padding()

            Divider()

            // 右画面:Text(出力欄)
            VStack(alignment: .leading) {
                Text("👀 出力プレビュー")
                    .font(.headline)
                ScrollView {
                    Text(text)
                        .padding()
                        .frame(minHeight: 200, alignment: .topLeading)
                        .border(Color.blue.opacity(0.3))
                }
            }
            .padding()
        }
        .frame(height: 300)
    }
}

#Preview {
    ContentView()
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?