본문 바로가기
Language/Swift

SwiftUI를 이용한 여러 줄의 텍스트를 입력하기 (TextEditor)

by IFLA 2022. 11. 25.

 

글을 입력할 때 여러 문장으로 이루어진 장문을 써야하는 경우도 있다. 그럴때는 SwiftUI 에서는 TextEditor 뷰를 이용해 장문의 글을 입력 및 나타낸다.

 

기본 코드

struct ContentView: View {
	@State private var text: String = "Enter some text"

	var body: some View {
		VStack {
			TextEditor(text: $text)
				.padding()
				.foregroundColor(Color.black)
				.font(.custom("원하는글꼴", size: 20))
				.lineSpacing(5) // 줄 간격
				.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 300)
				.border(Color.blue, width: 1)

			Spacer()
		}
	}
}

 

실행 화면

수정될 때 액션 취하기

struct ContentView: View {
	var body: some View {
		VStack {
			TextEditor(text: $text)
				.onChange(of: text) { value in
					print("텍스트 : \\(text)")	
				}
		}
	}
}

 


개발자 Document

https://developer.apple.com/documentation/swiftui/texteditor

 

Apple Developer Documentation

 

developer.apple.com

 

댓글


\