UIViewRepresentable how do you change UIToolBar UIBarButtonItem image when it is selected?

27 Views Asked by At

I am trying to toggle the UIImage used for the UIBarButtonItem when it is selected, but the UITextView is not updating, does anyone know why this is? I am not that familiar with UIKit so I do apologise if the answer is obvious.

Any help would be greatly appreciated!

import Foundation
import SwiftUI
import UIKit

struct Example: UIViewRepresentable {
    
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
    
    func makeUIView(context: Context) -> UITextView {
        context.coordinator.textView
    }
    
    func updateUIView(_ uiView: UITextView, context: Context) {}
    
    class Coordinator: NSObject, UITextViewDelegate {
        
        private var buttonSelected = false
        
        lazy var textView: UITextView = {
            let textView = UITextView()
            textView.delegate = self
            // make toolbar
            let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textView.frame.size.width, height: 44))
            // make toolbar button
            let underlineButton = UIBarButtonItem(
                image: UIImage(systemName: self.buttonSelected ? "person" : "person.fill"),
                style: .plain,
                target: self,
                action: #selector(toggleButtonSelected))
            toolBar.items = [underlineButton]
            textView.inputAccessoryView = toolBar
            return textView
        }()
        
        var stringDidChange: ((String) -> ())?
        
        func textViewDidChange(_ textView: UITextView) {
            stringDidChange?(textView.text)
        }
        
        @objc func toggleButtonSelected() {
            self.buttonSelected.toggle()
        }
    }
}
0

There are 0 best solutions below