Reputation: 580
I currently have a TextEditor, and I want to be able to add text formatting like in the notes app like this:
I've tried with UITextView.allowsEditingTextAttributes = true
but it didn't seem to work.
Any ideas will be highly appreciated. :)
Upvotes: 7
Views: 3302
Reputation: 236260
You can create a custom TextView UIViewRepresentable and set allowsEditingTextAttributes to true there:
create a new Swift file called TextView.swift
import SwiftUI
struct TextView: UIViewRepresentable {
@Binding var attributedText: NSMutableAttributedString
@State var allowsEditingTextAttributes: Bool = false
@State var font: UIFont?
func makeUIView(context: Context) -> UITextView {
UITextView()
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.attributedText = attributedText
uiView.allowsEditingTextAttributes = allowsEditingTextAttributes
uiView.font = font
}
}
Then you can add it to your content view:
import SwiftUI
struct ContentView: View {
@State var attributedText = NSMutableAttributedString(string: "")
var body: some View {
TextView(attributedText: $attributedText, allowsEditingTextAttributes: true, font: .systemFont(ofSize: 32))
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Upvotes: 6