A SwiftUI view that can display and edit long-form text or display a prompt when the editor's content is empty.
- Customizable UI: Easily integrate and style the editor as same as
SwiftUI.TextEditor
- Cross-Platform: Compatible with:
- iOS 15.0+
- macOS 12.0+.
- visionOS 1.0+.
- Swift Package Manager: Simple integration via SPM.
Add PromptTextEditor
to your project via Swift Package Manager:
- Open Xcode and go to File > Add Packages.
- Enter the URL of this repository:
https://github.com/tphduy/PromptTextEditor
- Choose the latest version and add the package to your project.
To use PromptTextEditor
, import the module and add the editor to your SwiftUI view.
import PromptTextEditor
struct ContentView: View {
@State private var text: String = ""
var body: some View {
PromptTextEditor(text: $text, prompt: Text("Lorem ipsum"))
}
}
You can provide custom prompt logic and adjust the appearance to suit your application's needs, as same as SwiftUI.TextEditor
.
In the code example below, if you want to use contentMargins(_:for:), you need to specify the same value for the promptOffset
parameter when initializing the PromptTextEditor
. This is because contentMargins(_:for:) cannot currently be read from the environment. Failing to align these values will result in the prompt being incorrectly positioned relative to the user's input.
struct ContentView: View {
@State var text: String = ""
@State var selection: TextSelection?
@FocusState var isFocused: Bool
var body: some View {
NavigationStack {
PromptTextEditor(
text: $text,
selection: $selection,
prompt: Text("How was your day?"),
promptOffset: CGSize(width: 16, height: 16)
)
.font(.title)
.focused($isFocused)
.contentMargins(16)
.background(Color.secondary.opacity(isFocused ? 0.4 : 0.2))
.scrollContentBackground(.hidden)
#if os(visionOS)
.clipShape(RoundedRectangle(cornerRadius: 24))
#else
.clipShape(RoundedRectangle(cornerRadius: 8))
#endif
#if os(iOS)
.padding()
#else
.padding(32)
#endif
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") {
isFocused = false
}
}
}
.navigationTitle("Text Editor")
}
}
}
Contributions are welcome! If you find a bug or have a feature request, feel free to open an issue or submit a pull request.
PromptTextEditor
is released under the MIT License. See the LICENSE file for more information.