PencilKit in SwiftUI - ios

I'm trying to use PencilKit in SwiftUI.
How can I detect in the updateUIView-function, which Binding-variable was updated? For example I don't want to clear the canvas when changing the color.
And is there a better way to clear the canvas than toggling a boolean? Toggling a boolean forces the updateUIView-function to execute.
import SwiftUI
import UIKit
import PencilKit
struct ContentView: View {
#State var color = UIColor.black
#State var clear = false
var body: some View {
VStack{
PKCanvas(color: $color, clear:$clear)
VStack(){
Button("Change to BLUE"){ self.color = UIColor.blue }
Button("Change to GREEN"){ self.color = UIColor.green }
Button("Clear Canvas"){ self.clear.toggle() }
}
}
}
}
struct PKCanvas: UIViewRepresentable {
class Coordinator: NSObject, PKCanvasViewDelegate {
var pkCanvas: PKCanvas
init(_ pkCanvas: PKCanvas) {
self.pkCanvas = pkCanvas
}
}
#Binding var color:UIColor
#Binding var clear:Bool
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> PKCanvasView {
let canvas = PKCanvasView()
canvas.tool = PKInkingTool(.pen, color: color, width: 10)
canvas.delegate = context.coordinator
return canvas
}
func updateUIView(_ canvasView: PKCanvasView, context: Context) {
// clears the canvas
canvasView.drawing = PKDrawing()
// sets a new color
canvasView.tool = PKInkingTool(.pen, color: color, width: 10)
}
}

This will do the trick:
func updateUIView(_ canvasView: PKCanvasView, context: Context) {
if clear != context.coordinator.pkCanvas.clear{
canvasView.drawing = PKDrawing()
}
canvasView.tool = PKInkingTool(.pen, color: color, width: 10)
}

I observed similar pattern many times, and here we get intercommunication between SwiftUI-value-declarative-state-managed world and xKit-OOP-imperative-action-managed world... and there are attempts either to put everything from one to another, or vice versa...
I've got a mind that probably it would be better to keep each nature for each and have some mediator or actor between two... so for your use-case I'd think that I would go different way, say (scratchy, not tested, for consideration):
struct ContentView: View {
//#State var color = UIColor.black // < both these have nothing to ContentView
//#State var clear = false
let pkActor = PKCanvasActor() // < mediator, reference type
var body: some View {
VStack{
PKCanvas(actor: pkActor)
VStack(){
Button("Change to BLUE"){ self.pkActor.use(color: UIColor.blue) }
Button("Change to GREEN"){ self.pkActor.use(color: UIColor.green) }
Button("Clear Canvas"){ self.pkActor.clear() }
}
}
}
}
somewhere here
func makeUIView(context: Context) -> PKCanvasView {
let canvas = PKCanvasView()
self.actor.canvas = canvas // but think to avoid cycle reference
and pure-OOP part
class PKCanvasActor {
var canvas: PKCanvasView
func use(color: Color) {
// do anything with canvas color
}
func clear() {
canvas.drawing = PKDrawing()
}
// ... any more actions
}
Of course there simple approach I proposed for similar scenario in SwiftUI Button interact with Map... but above way looks more preferable for me.
Remark: one might say the Coordinator is for this purpose, but its life-time is managed by SwiftUI-internals and it participate in those internal workflows, so I'd avoid intruding into those relationships...

Related

Hide Tools In PKCanvasView In SwiftUI

I have an iOS app which needs to capture user's signature
UI should be like this
I tried this using pencilKit as follows but,
It shows all the tools I don't need them to be visible
SwiftUIView
struct HandSignatureView: View {
var body: some View {
VStack {
Text("Place Your Signature Here")
.font(.title2)
.foregroundColor(.blue)
SignaturePadView()
}
.preferredColorScheme(.light)
}
}
UIViewRepresentable
struct SignaturePadView : UIViewRepresentable {
var canvasView = PKCanvasView()
let picker = PKToolPicker.init()
func makeUIView(context: Context) -> PKCanvasView {
self.canvasView.tool = PKInkingTool(.pen, color: .black, width: 15)
self.canvasView.becomeFirstResponder()
return canvasView
}
func updateUIView(_ uiView: PKCanvasView, context: Context) {
picker.addObserver(canvasView)
picker.setVisible(true, forFirstResponder: uiView)
DispatchQueue.main.async {
uiView.becomeFirstResponder()
}
}
}
This is the output I Got
picker.setVisible(false, forFirstResponder: uiView)
Hides tools but it draws nothing
If there's any good library I can use please be kind enough to share
Any Help will be appreciated Thank You !

How do I change the background colour of a list in swiftui? [duplicate]

I'm trying to recreate an UI I built with UIKit in SwiftUI but I'm running into some minor issues.
I want the change the color of the List here, but no property seems to work as I expects. Sample code below:
struct ListView: View {
#EnvironmentObject var listData: ListData
var body: some View {
NavigationView {
List(listData.items) { item in
ListItemCell(item: item)
}
.content.background(Color.yellow) // not sure what content is defined as here
.background(Image("paper-3")) // this is the entire screen
}
}
}
struct ListItemCell: View {
let item: ListItem
var body: some View {
NavigationButton(destination: Text(item.name)) {
Text("\(item.name) ........................................................................................................................................................................................................")
.background(Color.red) // not the area I'm looking for
}.background(Color.blue) // also not the area I'm looking for
}
}
Ok, I found the solution for coloring the list rows:
struct TestRow: View {
var body: some View {
Text("This is a row!")
.listRowBackground(Color.green)
}
}
and then in body:
List {
TestRow()
TestRow()
TestRow()
}
This works as I expect, but I have yet to find out how to then remove the dividing lines between the rows...
This will set the background of the whole list to green:
init() {
UITableView.appearance().separatorStyle = .none
UITableViewCell.appearance().backgroundColor = .green
UITableView.appearance().backgroundColor = .green
}
struct ContentView: View {
var strings = ["a", "b"]
var body: some View {
List {
ForEach(strings, id: \.self) { string in
Text(string)
}.listRowBackground(Color.green)
}
}
}
You can do it by changing UITableView's appearance.
UITableView.appearance().backgroundColor = UIColor.clear
just put this line in Appdelegate's didFinishLaunchingWithOptions method.
In replace of UIColor.clear set whatever color you want to add in background color of list.
Changing Background Color
As other have mentioned, changing the UITableView background will affect all other lists in your app.
However if you want different background colors you can set the default to clear, and set the background color in swiftui views like so:
List {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
// Ignore safe area to take up whole screen
.background(Color.purple.ignoresSafeArea())
.onAppear {
// Set the default to clear
UITableView.appearance().backgroundColor = .clear
}
You probably want to set the tableview appearance earlier, such as in the SceneDelegate or root view like so:
// SceneDelegate
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = scene as? UIWindowScene else {
print("Returning because screne does not exist")
return
}
// Set here
UITableView.appearance().backgroundColor = .clear
let contentView = ContentView()
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
// Root App View
#main
struct ListBackgroundApp: App {
init() {
UITableView.appearance().backgroundColor = .clear
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
2022
MacOS Solution
The following code makes ALL OF Lists background color transparent:
// Removes background from List in SwiftUI
extension NSTableView {
open override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
backgroundColor = NSColor.clear
if let esv = enclosingScrollView {
esv.drawsBackground = false
}
}
}
..........
..........
..........
the following code makes ALL OF TextEditors background color transparent:
extension NSTextView {
open override var frame: CGRect {
didSet {
backgroundColor = .clear
drawsBackground = true
}
}
}
There is an argument: listRowBackground() in SwiftUI, but if you use List directly to iterate the data collection, it doesn't work.
Here is my workaround:
List {
// To make the background transparent, we have we use a ForEach as a wrapper
ForEach(files) {file in
Label(
title: { Text(file.name ?? fileOptionalFiller).lineLimit(listRowTextLineLimit) },
icon: { AppIcon.doc.foregroundColor(.primary) }
)
}
.listRowBackground(Color.primary.colorInvert())
}
Basically, listRowBackground() works if you use a ForEach inside List.
I was able to get the whole list to change color by using colorMultiply(Color:). Just add this modifier to the end of the list view, and then the padding will push the table to the device edges. For example:
List {...}.colorMultiply(Color.green).padding(.top)
https://www.hackingwithswift.com/quick-start/swiftui/how-to-adjust-views-by-tinting-and-desaturating-and-more
I do not know what is the connection but if you wrap the list with Form it is working.
Form {
List(viewModel.currencyList, id: \.self) { currency in
ItemView(item: currency)
}
.listRowBackground(Color("Primary"))
.background(Color("Primary"))
}
iOS 16 provides a modifier to control the background visibility of List (and other scrollable views): scrollContentBackground(_:)
You can hide the standard system background via .hidden. If you provide a background as well, that will become visible.
List {
Text("One")
Text("Two")
}
.background(Image("MyImage"))
.scrollContentBackground(.hidden)
You may also want to customize the background of list rows - the individual cells - and separators. This can be done like so:
List {
Section("Header") {
Text("One")
Text("Two")
.listRowBackground(Color.red)
}
.listRowBackground(Color.clear)
.listRowSeparator(.hidden)
}
.scrollContentBackground(.hidden)
struct Details: View {
var body: some View {
Spacer().overlay(
List {
Text("Hello World!").font(.title2)
.listRowBackground(Color.clear)
Text("Hello World again").font(.title2)
.listRowBackground(Color.clear)
}.onAppear() {
UITableView.appearance().backgroundColor = UIColor.green
UITableViewCell.appearance().backgroundColor = UIColor.green
}
)
}
}
The answer by Islom Alimov https://stackoverflow.com/a/59970379/9439097 seems to be the best implementation so far in my opinion.
Only drawback: this also changes the background color of all other list views in your app, so you need to manually change them back unless you want the same color everywhere.
Here is an example view:
import SwiftUI
struct TestView1: View {
init(){
UITableView.appearance().backgroundColor = UIColor(Color.clear)
}
#State var data = ["abc", "def"]
var body: some View {
VStack {
List {
ForEach(data, id: \.self) {element in
Text("\(String(describing: element))")
}
.background(Color.green)
.listRowBackground(Color.blue)
}
.background(Color.yellow)
Spacer()
Color.red
}
}
}
struct TestView1_Previews: PreviewProvider {
static var previews: some View {
TestView1()
}
}
produces:
Someone may find this useful if attempting to create a floating type cell with SwiftUI using .listRowBackground and applying .padding
var body: some View {
NavigationView {
List {
ForEach (site) { item in
HStack {
Text(String(item.id))
VStack(alignment: .leading) {
Text(item.name)
Text(item.crop[0])
}
}.listRowBackground(Color.yellow)
.padding(.trailing, 5)
.padding(.leading, 5)
.padding(.top, 2)
.padding(.bottom, 2))
}
}
.navigationBarTitle(Text("Locations"))
}
}
I assume the listRowPlatterColor modifier should do this, but isn't as of Xcode 11 Beta 11M336w
var body: some View {
List(pokemon) { pokemon in
PokemonCell(pokemon: pokemon)
.listRowPlatterColor(.green)
}
}
.colorMultiply(...)
As an option you can .colorMultiply(Color.yourColor) modifier.
Warning: this does not change the color! This only applies the Multiply modifier to the current color. Please read the question before any action, because you are probably looking for: "How to CHANGE the background color of a List in SwiftUI" and this will not work for you. ❄️
Example:
List (elements, id:\.self ) { element in
Text(element)
}
.colorMultiply(Color.red) <--------- replace with your color
For me, a perfect solution to change the background of List in SwiftUI is:
struct SomeView: View {
init(){
UITableView.appearance().backgroundColor = UIColor(named: "backgroundLight")
}
...
}
List is not perfect yet.
An option would be to use it like this -> List { ForEach(elements) { }} instead of List($elements)
On my end this is what worked best up to now.
Like #FontFamily said, it shouldn't break any List default behaviors like swiping.
Simply Add UITableView appearance background color in init() method and add list style (.listStyle(SidebarListStyle()). Don't forget to import UIKit module
struct HomeScreen: View {
init() {
UITableView.appearance().backgroundColor = .clear
}
let tempData:[TempData] = [TempData( name: "abc"),
TempData( name: "abc"),
TempData( name: "abc"),
TempData( name: "abc")]
var body: some View {
ZStack {
Image("loginBackgound")
.resizable()
.scaledToFill()
List{
ForEach(tempData){ data in
Text(data.name)
}
}
.listStyle(SidebarListStyle())
}
.ignoresSafeArea(edges: .all)
}
}
Using UITableView.appearance().backgroundColor is not a good idea as it changes the backgroundColor of all tables. I found a working solution for color changing at the exact table you selected in iOS 14, 15.
We will change the color using a modifier that needs to be applied inside the List
extension View {
func backgroundTableModifier(_ color: UIColor? = nil) -> some View {
self.modifier(BackgroundTableModifier(color: color))
}
}
Our task is to find the UITableView and after that change the color.
private struct BackgroundTableModifier: ViewModifier {
private let color: UIColor?
#State private var tableView: UITableView?
init(color: UIColor?) {
self.color = color
}
public func body(content: Content) -> some View {
if tableView?.backgroundColor != color {
content
.overlay(BackgroundTableViewRepresentable(tableBlock: { tableView in
tableView.backgroundColor = color
self.tableView = tableView
}))
} else {
content
}
}
}
private struct BackgroundTableViewRepresentable: UIViewRepresentable {
var tableBlock: (UITableView) -> ()
func makeUIView(context: Context) -> BackgroundTableView {
let view = BackgroundTableView(tableBlock: tableBlock)
return view
}
func updateUIView(_ uiView: BackgroundTableView, context: Context) {}
}
class BackgroundTableView: UIView {
var tableBlock: (UITableView) -> ()
init(tableBlock: #escaping (UITableView) -> ()) {
self.tableBlock = tableBlock
super.init(frame: .zero)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
if let tableView = findTableView(in: self) {
tableBlock(tableView)
}
}
private func findTableView(in view: UIView) -> UITableView? {
if let tableView = view as? UITableView {
return tableView
}
if let superView = view.superview {
return findTableView(in: superView)
}
return nil
}
}
In order to find UITableView, the modifier must be inside the List. Naturally, you need to ensure that the modifier is called only once, you do not need to apply it to each row. Here is an example of usage
List {
rows()
.backgroundTableModifier(.clear)
}
func rows() -> some View {
ForEach(0..<10, id: \.self) { index in
Row()
}
}
In iOS 16, we got a native way to do this via scrollcontentbackground modifier.
You can either change the color by setting a color (ShapeStyle) to scrollcontentbackground.
List {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
.scrollContentBackground(Color.pink)
Or you can hide the background .scrollContentBackground(.hidden) and set a custom one with .backgroud modifier.
List {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
.background {
Image("ventura")
}
.scrollContentBackground(.hidden)
I've inspired some of the configurator used to config per page NavigationView nav bar style and write some simple UITableView per page configurator not use UITableView.appearance() global approach
import SwiftUI
struct TableViewConfigurator: UIViewControllerRepresentable {
var configure: (UITableView) -> Void = { _ in }
func makeUIViewController(context: UIViewControllerRepresentableContext<TableViewConfigurator>) -> UIViewController {
UIViewController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<TableViewConfigurator>) {
let tableViews = uiViewController.navigationController?.topViewController?.view.subviews(ofType: UITableView.self) ?? [UITableView]()
for tableView in tableViews {
self.configure(tableView)
}
}
}
Then there is UIView extension needed to find all UITableViews
extension UIView {
func subviews<T:UIView>(ofType WhatType:T.Type) -> [T] {
var result = self.subviews.compactMap {$0 as? T}
for sub in self.subviews {
result.append(contentsOf: sub.subviews(ofType:WhatType))
}
return result
}
}
And usage at the end is:
List {
}.background(TableViewConfigurator {
$0.backgroundColor = .red
})
Maybe one thing should be improved that is usage of navigationController?.topViewController to make it work even without navigationController in view controllers hierarchy
If anyone came here looking for solutions for background in landscape not full width on iPhone X/11 try:
.listRowBackground(Color("backgroundColour").edgesIgnoringSafeArea(.all))
If you want to avoid setting the appearance for all table views globally, you can combine UITableView.appearance(whenContainedInInstancesOf:) with UIHostingController. Thanks DanSkeel for the comment you left above pointing this out. This is how I used it:
public class ClearTableViewHostingController<Content>: UIHostingController<Content> where Content: View {
public override func viewDidLoad() {
UITableView.appearance(whenContainedInInstancesOf: [ClearTableViewHostingController<Content>.self]).backgroundColor = .clear
}
}
You can use ClearTableViewHostingController like this:
let view = MyListView()
let viewController = ClearTableViewHostingController(coder: coder, rootView: view)
Then in your view you can set the list background color like so:
List {
Text("Hello World")
}
.background(Color.gray)
Make extension List like:
extension List{
#available(iOS 14, *)
func backgroundList(_ color: Color = .clear) -> some View{
UITableView.appearance().backgroundColor = UIColor(color)
return self
}
}
you can use introspect library from Github to set the background color for the underlying table view like this:
List { ... } .introspectTableView { tableView in
tableView.backgroundColor = .yellow
}
For some reason color change is not working, you can try the .listStyle to .plain
Code:
struct ContentView: View {
var body: some View {
VStack {
Text("Test")
List {
ForEach(1 ..< 4) { items in
Text(String(items))
}
}
.listStyle(.plain)
}
}
Changing background did not work for me, because of the system background. I needed to hide it.
List(examples) { example in
ExampleRow(example: example)
}.background(Color.white.edgesIgnoringSafeArea(.all))
.scrollContentBackground(.hidden)
Xcode Version 12.4
The Background property worked for me, but with the mandatory use of Opacity.
Without opacity it is not work.
List {
ForEach(data, id: \.id) { (item) in
ListRow(item)
.environmentObject(self.data)
}
}
.background(Color.black)
.opacity(0.5)

UITextView inputAccessoryView not behaving properly on safe area phones?

I am trying use UIKit's UITextView in an swiftUI project using UIViewRepresentable. Everything works great but I am facing some issue with inputAccessoryView on phones with safe area.
My inputAccessoryView is a swiftUI view wrapped in UIHostingController which lets me use swiftUI views as UIView.
I have attached my code and some images, To simplify my issue I am using simple swiftUI colorView as inputAccessoryView. As you can see the swiftUI view moves out of the frame of inputAccessoryView when it comes near bottom safe area. When you swipe down to close the keyboard it disappears weirdly. I have tried everything but could not find the solution. Can you please help me?
Thank You!
UIViewRepresentable, UITextView
struct UITextViewWrapper: UIViewRepresentable {
#Binding var text: String
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.text = text
textView.inputAccessoryView = makeKeyboardBar()
textView.keyboardDismissMode = .interactive
textView.alwaysBounceVertical = true
textView.delegate = context.coordinator
textView.becomeFirstResponder()
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
//
}
class Coordinator: NSObject, UITextViewDelegate {
let parent: UITextViewWrapper
init(_ parent: UITextViewWrapper) {
self.parent = parent
}
func textViewDidChange(_ textView: UITextView) {
parent.text = textView.text
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
func makeKeyboardBar() -> UIView {
let swiftUIView = ColorView()
let hostingController = UIHostingController(rootView: swiftUIView)
let uiView = hostingController.view!
uiView.frame = CGRect(origin: .zero, size: hostingController.sizeThatFits(in: uiView.frame.size))
uiView.layer.borderWidth = 1
uiView.layer.borderColor = UIColor.red.cgColor
return uiView
}
}
SwiftUI View to use as inputAccessoryView
struct ColorView: View {
var body: some View {
Color.yellow
.frame(height: 55)
}
}
ContentView
struct ContentView: View {
#State private var text = "Hello World"
var body: some View {
UITextViewWrapper(text: $text)
}
}
image
SwiftUI has own safe area tracking so you have to manage safe area behaviour explicitly inside SwiftUI view, like
var body: some View {
Color.yellow.edgesIgnoringSafeArea(.bottom) // << here !!
.frame(height: 55)
}

Change colour of Picker within NavigationView

I'm trying to embed this NavigationView within a larger view but nothing I seem to set will change to background colour of the Picker within this view.
When I do the following, everything other than the Picker itself is set to black, but the picker remains white, like so...
example image
There may be a much better setup to get the effect I am after but not knowing that, how do I change the Picker Colour also?
struct ContentView: View {
#State var value = ""
init(){
UITableView.appearance().backgroundColor = .clear
UINavigationBar.appearance().backgroundColor = .clear
}
var body: some View {
NavigationView {
ZStack {
Color.black
.ignoresSafeArea()
Form {
Picker(selection: $value, label: Text("This")) {
Text("1").tag("1")
Text("2").tag("2")
Text("3").tag("3")
Text("4").tag("4")
}
}
}
}
}
}
Use listRowBackground for that.
Picker(selection: $value, label: Text("this")) {
...
}.listRowBackground(Color.green)
In order to change the background color of the cells in the opened picker, you'll have to set them through UIKit.
extension View {
func cellBackgroundColor(_ uiColor: UIColor) -> some View {
background(TableCellGrabber { cell in
cell.backgroundView = UIView()
cell.backgroundColor = uiColor
})
}
}
struct TableCellGrabber: UIViewRepresentable {
let configure: (UITableViewCell) -> Void
func makeUIView(context: Context) -> UIView {
UIView()
}
func updateUIView(_ uiView: UIView, context: Context) {
DispatchQueue.main.async {
if let cell: UITableViewCell = uiView.parentView() {
configure(cell)
}
}
}
}
extension UIView {
func parentView<T: UIView>() -> T? {
if let v = self as? T {
return v
}
return superview?.parentView()
}
}
Usage:
Picker(selection: $value, label: Text("this")) {
Text("1").tag("1").cellBackgroundColor(.red)
Text("2").tag("2").cellBackgroundColor(.red)
Text("3").tag("3").cellBackgroundColor(.red)
Text("4").tag("4").cellBackgroundColor(.red)
}
Or you can use special Group view to apply it to all grouped items.
Picker(selection: $value, label: Text("this")) {
Group {
Text("1").tag("1")
Text("2").tag("2")
Text("3").tag("3")
Text("4").tag("4")
}.cellBackgroundColor(.red)
}

Send data changes from UIKit, Wrapped inside UIViewRepresentable, to SwiftUI, and Rich Text Editor problem

I am working on a SwiftUI project, the functionalities it required is to make a Rich Text Editor on IOS.
The approach I am following is fairly simple, I used cbess/RichTextEditor link originally written in UIKit and import it into SwiftUI. To run the imported UIView, I wrap the view inside one UIViewRpresentable and add it into the ContentView struct of SwiftUI.
Now, I want to publish the data inside UIView and assign it to one of #state ContentView owns.
The code structure look similar to this:
For the ContentView (SwiftUI)
struct ContentView: View {
#State var textHtml: String = "" //I want all changes come from UIView be stored inside this
var body: some View {
VStack {
Cbess(
frameEditor: CGRect(x: 0, y: 40, width: 360, height: 400)
)
}
}
}
For the UiViewRepresentable
struct Cbess : UIViewRepresentable{
let frameEditor : CGRect
func makeUIView(context: Context) -> UIView {
let frameEditor = RichEditorView(frame: frameEditor)
let uiView : UIView = UIView()
uiView.addSubview(editorView)
return uiView
}
func updateUIView(_ uiView: UIView, context: Context) {
}
}
For the UiView(Simplified)
#objcMembers open class RichEditorView: UIView, {
var contentHTML : String // This variable get updated regularly
}
One additional question is that I want to make a Rich Text Editor by solely SwiftUI. How can I achieve it? Can you give me some keywords? Some Repo?
Any help is very appreciated! Thanks for read this whole question.
Use #Binding and delegate.
UIViewRepresentable view
struct Cbess : UIViewRepresentable {
#Binding var textHtml: String
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> RichEditorView {
let editorView = RichEditorView()
editorView.delegate = context.coordinator
return editorView
}
func updateUIView(_ uiView: RichEditorView, context: Context) {
}
class Coordinator: NSObject, RichEditorDelegate {
var parent: Cbess
init(_ parent: Cbess) {
self.parent = parent
}
// Use delegate here
func richEditor(_ editor: RichEditorView, contentDidChange content: String) {
self.parent.textHtml = content
print(content)
}
}
}
Your content view:
struct ContentView: View {
#State var textHtml: String = ""
var body: some View {
VStack {
Cbess(textHtml: $textHtml)
.frame(width: 360, height: 400)
Text("Print----\n\(textHtml)")
}
}
}

Resources