Post

Replies

Boosts

Views

Activity

Reply to Navigation Stack
Here are some screenshot images which may help. My GUI is shown in the image below: And the code: import SwiftUI import UIKit public struct ContentView6: View {     @State public var tabSelection = 2  // The app will open on this page.     public var body: some View {         TabView(selection: $tabSelection) { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             helpView()                 .tabItem {                     Image(systemName: "questionmark.circle.fill") // SF symbol                     Text("Help") // Text beneath symbol                 }                 .tag(0)  // 1st item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             selectPhotoView()                 .tabItem {                     Image(systemName: "photo") // SF symbol                     Text("Photos") // Text beneath symbol                 }                 .tag(1)  // 2nd item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             takePictureView()                 .tabItem {                     Image(systemName: "camera") // SF symbol                     Text("Camera") // Text beneath symbol                 }                 .tag(2)  // 3rd item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             historyView()                 .tabItem {                     Image(systemName: "clock") // SF symbol                     Text("History") // Text beneath symbol                 }                 .tag(3)  // 4th item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             settingsView()                 .tabItem {                     Image(systemName: "gearshape") // SF symbol                     Text("Settings") // Text beneath symbol                 }                 .tag(4)  // 5th item on menu bar         }     } } // Action on 'Help' tab: struct helpView: View {     var body: some View {         ContentView5().edgesIgnoringSafeArea(.all) // Naviagtion Stacks (Help page)     } } // Action on 'Photos' tab: struct selectPhotoView: View {     var body: some View {         storyboardview2().edgesIgnoringSafeArea(.all) // ViewController2 (Photos page)     } } // Action on 'Camera' tab: struct takePictureView: View {     var body: some View {         storyboardview().edgesIgnoringSafeArea(.all) // ViewController (Camera page)     } } // Action on 'History' tab: struct historyView: View {     var body: some View {         storyboardview3().edgesIgnoringSafeArea(.all) // ViewController3 = OCR - does not belog here (History page)     } } // Action on 'Settings' tab: struct settingsView: View {     var body: some View {         //Tutorial().edgesIgnoringSafeArea(.all) // Tutorial - does not belong here (Settings page)         SettingsView()     } } struct ContentView6_Previews: PreviewProvider {     static var previews: some View {         ContentView6()     } } And the tutorial with the more info button is called on tab 0, this is under ContentView5. An image of this is shown below:
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Toggle
I have rewritten the code for my button as shown below. It no longer crashes however I can not see the button / it is not visible on the simulator. Any thoughts would be great. Many thanks import SwiftUI import UIKit import Vision class ViewController2: UIViewController {     @IBOutlet weak var imageView: UIImageView!     @IBOutlet weak var textView: UITextView!     @IBOutlet weak var activityIndicator: UIActivityIndicatorView!     @IBOutlet weak var button: UIButton!     @IBOutlet weak var shareButton: UIButton!     override func viewDidLoad() {         super.viewDidLoad()         button.backgroundColor = .systemCyan // Background colour of the select photo button         button.setTitle("Select Photo", for: .normal) // Button text         button.setTitleColor(.white, for: .normal) // Button text Colour         // Rounding the edges of the 'Select Photo' button:         button.layer.cornerRadius = 25         button.layer.borderWidth = 20         button.layer.borderColor = UIColor.systemCyan.cgColor         // Rounding the edges of the 'Share' button:         shareButton.layer.cornerRadius = 25         shareButton.layer.borderWidth = 10         shareButton.layer.borderColor = UIColor.systemCyan.cgColor         stopAnimating() // Activity indicator disappears     }     // Defining the activity indicators show and spin     private func startAnimating() {         self.activityIndicator.startAnimating()     }     // Defining the activity indicators stop and hide     private func stopAnimating(){         self.activityIndicator.stopAnimating()     }     @IBAction func selectPhotoButton(_ sender: Any) { // When selectPhoto button is pressed,         SelectPhotoButtonPressed() // run the function SelectPhotoButtonPressed.     }     private func SelectPhotoButtonPressed(){         if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){             let imageSelector = UIImagePickerController() // Apple's interface for taking pictures and loading items from camera roll             imageSelector.sourceType = .photoLibrary // Opens the device's photo library             imageSelector.delegate = self // Leaves the UIImagePickerController when a picture is selected             self.present(imageSelector, animated: true, completion: nil) // Present the imageSelector         }     }     // Text Recognition     // Create request     var request = VNRecognizeTextRequest(completionHandler: nil)     private func VisionOCR(image: UIImage?){         var textString = "" // Variable textString = string         // Create completion handler         request = VNRecognizeTextRequest(completionHandler: { (request, error)in  // Locates all the text in the image.             // Results are in the request             guard let results = request.results as?[VNRecognizedTextObservation] else {fatalError("Recieved Invalid Observation")}             for visionResult in results{                 guard let recognisedText = visionResult.topCandidates(1).first else{ // Text stored in chronological order.                     print("No text")                     continue                 }                 textString += "\n\(recognisedText.string)"                 DispatchQueue.main.async{ // FIFO queue                     self.stopAnimating() // Hide the activityIndicator                     self.textView.text = textString // Assign the textView the recoginsed text                 }             }         })         // Properties         request.minimumTextHeight = 0.03125 // Default mimnimum height for text to be recognised in comparison to image, (1/32).         request.recognitionLevel = .accurate // Choice between accurate and fast.         request.recognitionLanguages = ["en_UK", "en-US", "fr-FR", "it-IT", "de-DE", "es-ES", "pt-BR", "zh-Hans", "zh-Hant", "yue-Hans", "yue-Hant", "ko-KR", "ja-JP", "ru-RU", "uk-UA"] // Recognisable languages.         request.usesLanguageCorrection = true // Applies language correction.         let requests = [request] ![]("https://developer.apple.com/forums/content/attachment/802b997e-3c1d-400a-ad6a-a914a23599f7" "title=Simulator Screen Shot - iPhone 14 Pro Max - 2022-12-13 at 12.39.54.png;width=1290;height=2796")         // MARK: - Pop-up Button         let AccurateRecognition = { (action: UIAction) in             print(action.title) // do color change job             self.request.recognitionLevel = VNRequestTextRecognitionLevel.fast         }         let FastRecognition = { (action: UIAction) in             print(action.title) // do color change job             self.request.recognitionLevel = VNRequestTextRecognitionLevel.fast         }         lazy var popupButton: UIButton = {             let button = UIButton(primaryAction: nil)             button.menu = UIMenu(children: [                 UIAction(title: "Accurate", handler: AccurateRecognition),                 UIAction(title: "Fast", state: .on, handler: FastRecognition),             ])             button.showsMenuAsPrimaryAction = true             button.changesSelectionAsPrimaryAction = true // now its a pop-up button             return button         }()          func accessPopupButtonProperties() {             // Update to the currently set one             print(popupButton.menu?.selectedElements.first?.title ?? "") // get currenty set             // Update the selection             (popupButton.menu?.children[0] as? UIAction)?.state = .on         }         // Request handler         DispatchQueue.global(qos: .userInitiated).async{  // FIFO queue, qos (quality of service) determines priotity for scheduling tasks             guard let img = image?.cgImage else {fatalError("Missing image to scan")} // Variable image = computer generated image             // Create request handler             let requestHandler = VNImageRequestHandler(cgImage: img, options: [:])  // Performs Vision requests             // Send request to request handler             try? requestHandler.perform(requests) // Schedules Vision requests to be performed         }        } } extension ViewController2: UIImagePickerControllerDelegate, UINavigationControllerDelegate{     func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey :Any]){         picker.dismiss(animated: true, completion: nil)         startAnimating()         self.textView.text = ""         let image = info[UIImagePickerController.InfoKey.originalImage]as?UIImage         self.imageView.image = image         VisionOCR(image: image)     } } public struct storyboardview2: UIViewControllerRepresentable{     public func makeUIViewController(context content: Context) -> UIViewController {         let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)         let controller = storyboard.instantiateViewController(identifier: "selectPhoto")         return controller     }     public func updateUIViewController(_ uiViewController: UIViewController, context: Context) {     } }
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Toggle
In the image below, you can see that I have a file called SettingsTableViewCell which tries to access a variable called request.recognitionlevel. In the image below, you can see that I have another file called ViewController2, which defines and uses the variable request.recognition level. How can I make the variable request.recognition visible in the SettingsTableViewCell, so that's its value in ViewController2 can be changed from the button in SettingsTableView?
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Toggle
So, I have added the code shown below in my ViewController2, which defines the variable.         override func prepare(for segue: UIStoryboardSegue, sender: Any?) {             if let destination = segue.destination as? ViewController4 {                 destination.delegate = self             }         }         func updatetoAccurate(newName: String) {             request.recognitionLevel = .accurate // Choice between accurate and fast.         }         override func prepare2(for segue: UIStoryboardSegue, sender: Any?) {             if let destination = segue.destination as? ViewController4 {                 destination.delegate = self             }         } And I have added the code below in my ViewController4, which attempts to change the value of the variable:     let AccurateRecognition = { (action: UIAction) in         print("Accurate")         print(action.title) // do color change job         //request.recognitionLevel = .accurate // Choice between accurate and fast.         var delegate: UpdateViewController2?         delegate?.updatetoFast(newName: name)     }     let FastRecognition = { (action: UIAction) in         print("Fast")         print(action.title) // do color change job         //request.recognitionLevel = .fast // Choice between accurate and fast.         var delegate: UpdateViewController2?         delegate?.updatetoAccurate(newName: name)     } However, I still receive multiple errors as shown in the photos below. ViewController2: ViewController4:
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Toggle
Below I have attached the code for my ViewController4 and a screenshot of the error. Any thought in how to fix this would be great. import UIKit import SwiftUI class ViewController4: UIViewController, UpdateVC4 {     let stackView: UIStackView = {         let stack = UIStackView()         stack.axis = .vertical         stack.alignment = .center         stack.spacing = 20         return stack     }()     protocol UpdateVC4 {        func updateAccuracy(newAcc: VNRequestTextRecognitionLevel)     }     func updateAccuracy(newAcc: VNRequestTextRecognitionLevel) {         // Set accuracy value here         request.recognitionLevel = .fast // Choice between accurate and fast.     }     lazy public var popupButton: UIButton = {         let button = UIButton(primaryAction: nil)         button.menu = UIMenu(children: [             UIAction(title: "Accurate Recignition", state: .on, handler: updateAccuracy),             UIAction(title: "Fast Recognition",handler: updateAccuracy),         ])         button.showsMenuAsPrimaryAction = true         button.changesSelectionAsPrimaryAction = true // now its a pop-up button         return button     }()     override func viewDidLoad() {         super.viewDidLoad()         setupUI()     }     fileprivate func accessPopupButtonProperties() {         // Update to the currently set one         print(popupButton.menu?.selectedElements.first?.title ?? "") // get currenty set         // Update the selection         (popupButton.menu?.children[0] as? UIAction)?.state = .on     }     fileprivate func setupUI() {         view.backgroundColor = .systemBackground         stackView.translatesAutoresizingMaskIntoConstraints = false         popupButton.translatesAutoresizingMaskIntoConstraints = false         view.addSubview(stackView)         stackView.addArrangedSubview(popupButton)         NSLayoutConstraint.activate([             stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),             stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),             stackView.topAnchor.constraint(greaterThanOrEqualTo: view.topAnchor, constant: 100),             stackView.bottomAnchor.constraint(lessThanOrEqualTo: view.bottomAnchor, constant: -100),             stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),         ])     } } public struct storyboardview4: UIViewControllerRepresentable{     public func makeUIViewController(context content: Context) -> UIViewController {         let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)         let controller = storyboard.instantiateViewController(identifier: "Settings")         return controller     }     public func updateUIViewController(_ uiViewController: UIViewController, context: Context) {     } }
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Integrating the Touch Bar into an iOS and MacOS app.
The code for my GUI is shown below. I am thinking perhaps the class TouchBarViewController needs to be called here? Something else I require is that when the user clicks on one of the 5 items in the Touch Bar, it will change the tabSelection in my GUI accordingly. For example, if the user taps on the first item in the Touch Bar, they should be taken to HelpView()/ContentView5. Or if the user taps on the second item in the Touch Bar, they should be taken to the SelectPhotoView()/StoryboardView2, etc... Furthermore, if they use the mouse to click on one of the tabs in my GUI, the selected item will also need to change accordingly. Any thoughts on how to implement this would be most welcomed. Many thanks import SwiftUI import UIKit public struct ContentView6: View {     @State public var tabSelection = 2  // The app will open on this page.     public var body: some View {         TabView(selection: $tabSelection) { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             helpView()                 .tabItem {                     Image(systemName: "questionmark.circle.fill") // SF symbol                     Text("Help") // Text beneath symbol                 }                 .tag(0)  // 1st item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             selectPhotoView()                 .tabItem {                     Image(systemName: "photo") // SF symbol                     Text("Photos") // Text beneath symbol                 }                 .tag(1)  // 2nd item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             takePictureView()                 .tabItem {                     Image(systemName: "camera") // SF symbol                     Text("Camera") // Text beneath symbol                 }                 .tag(2)  // 3rd item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             historyView()                 .tabItem {                     Image(systemName: "clock") // SF symbol                     Text("History") // Text beneath symbol                 }                 .tag(3)  // 4th item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             settingsView()                 .tabItem {                     Image(systemName: "gearshape") // SF symbol                     Text("Settings") // Text beneath symbol                 }                 .tag(4)  // 5th item on menu bar         }     } } // Action on 'Help' tab: struct helpView: View {     var body: some View {         ContentView5().edgesIgnoringSafeArea(.all) // Naviagtion Stacks (Help page)     } } // Action on 'Photos' tab: struct selectPhotoView: View {     var body: some View {         storyboardview2().edgesIgnoringSafeArea(.all) // ViewController2 (Photos page)     } } // Action on 'Camera' tab: struct takePictureView: View {     var body: some View {         storyboardview().edgesIgnoringSafeArea(.all) // ViewController (Camera page)     } } // Action on 'History' tab: struct historyView: View {     var body: some View {         //storyboardview3().edgesIgnoringSafeArea(.all) // ViewController3 = OCR - does not belog here (History page)         storyboardview4().edgesIgnoringSafeArea(.all) // ViewController4 = OCR - does not belog here (History page)     } } // Action on 'Settings' tab: struct settingsView: View {     var body: some View {         //Tutorial().edgesIgnoringSafeArea(.all) // Tutorial - does not belong here (Settings page)         SettingsView()     } } struct ContentView6_Previews: PreviewProvider {     static var previews: some View {         ContentView6()     } } A screenshot of my GUI on Mac is shown below:
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Touch Bar
The code for my GUI is shown below. I am thinking perhaps the class TouchBarViewController needs to be called here? Something else I require is that when the user clicks on one of the 5 items in the Touch Bar, it will change the tabSelection in my GUI accordingly. For example, if the user taps on the first item in the Touch Bar, they should be taken to HelpView()/ContentView5. Or if the user taps on the second item in the Touch Bar, they should be taken to the SelectPhotoView()/StoryboardView2, etc... Furthermore, if they use the mouse to click on one of the tabs in my GUI, the selected item will also need to change accordingly. Any thoughts on how to implement this would be most welcomed. Many thanks import SwiftUI import UIKit public struct ContentView6: View {     @State public var tabSelection = 2  // The app will open on this page.     public var body: some View {         TabView(selection: $tabSelection) { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             helpView()                 .tabItem {                     Image(systemName: "questionmark.circle.fill") // SF symbol                     Text("Help") // Text beneath symbol                 }                 .tag(0)  // 1st item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             selectPhotoView()                 .tabItem {                     Image(systemName: "photo") // SF symbol                     Text("Photos") // Text beneath symbol                 }                 .tag(1)  // 2nd item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             takePictureView()                 .tabItem {                     Image(systemName: "camera") // SF symbol                     Text("Camera") // Text beneath symbol                 }                 .tag(2)  // 3rd item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             historyView()                 .tabItem {                     Image(systemName: "clock") // SF symbol                     Text("History") // Text beneath symbol                 }                 .tag(3)  // 4th item on menu bar ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             settingsView()                 .tabItem {                     Image(systemName: "gearshape") // SF symbol                     Text("Settings") // Text beneath symbol                 }                 .tag(4)  // 5th item on menu bar         }     } } // Action on 'Help' tab: struct helpView: View {     var body: some View {         ContentView5().edgesIgnoringSafeArea(.all) // Naviagtion Stacks (Help page)     } } // Action on 'Photos' tab: struct selectPhotoView: View {     var body: some View {         storyboardview2().edgesIgnoringSafeArea(.all) // ViewController2 (Photos page)     } } // Action on 'Camera' tab: struct takePictureView: View {     var body: some View {         storyboardview().edgesIgnoringSafeArea(.all) // ViewController (Camera page)     } } // Action on 'History' tab: struct historyView: View {     var body: some View {         //storyboardview3().edgesIgnoringSafeArea(.all) // ViewController3 = OCR - does not belog here (History page)         storyboardview4().edgesIgnoringSafeArea(.all) // ViewController4 = OCR - does not belog here (History page)     } } // Action on 'Settings' tab: struct settingsView: View {     var body: some View {         //Tutorial().edgesIgnoringSafeArea(.all) // Tutorial - does not belong here (Settings page)         SettingsView()     } } struct ContentView6_Previews: PreviewProvider {     static var previews: some View {         ContentView6()     } } A screenshot of my GUI on Mac is shown below:
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Integrating the Touch Bar into an iOS and MacOS app.
I have written some code in a separate file which is shown below. I don't know whether this code works or not because when I run my app on Mac, nothing appears on my Touch Bar. I am sure I need to call the class somewhere within my app but I don't know where. Any thought on this would be much appreciated. Many thanks. #if targetEnvironment(macCatalyst) import Cocoa class TouchBarViewController: NSViewController {     let button = NSTouchBarItem.Identifier("com.TouchBarCatalog.TouchBarItem.button")     let buttonBar = NSTouchBar.CustomizationIdentifier("com.TouchBarCatalog.buttonBar")     @IBOutlet weak var HelpButton: NSButton!     @IBOutlet weak var PhotosButton: NSButton!     @IBOutlet weak var CameraButton: NSButton!     @IBOutlet weak var HistoryButton: NSButton!     @IBOutlet weak var SettingsButton: NSButton! } // MARK: - Action Functions override func viewDidLoad() {     super.viewDidLoad() } override func makeTouchBar() -> NSTouchBar? {     let touchBar = NSTouchBar()     touchBar.delegate = self     touchBar.customizationIdentifier = buttonBar     touchBar.defaultItemIdentifiers = [button]     return touchBar } @IBAction func customize(_ sender: AnyObject) {     guard let touchBar = touchBar else { return }     for itemIdentifier in touchBar.itemIdentifiers {         guard let item = touchBar.item(forIdentifier: itemIdentifier) as? NSButtonTouchBarItem,             let button = item.view as? NSButton else { continue }         button.bezelColor = useCustomColor.state == NSControl.StateValue.on ? NSColor.systemYellow : nil     } } @IBAction func buttonAction(_ sender: AnyObject) {     if let button = sender as? NSButtonTouchBarItem {         print("\(#function): button with title \"\(button.title)\" is tapped")     } } } // MARK: - NSTouchBarDelegate extension TouchBarViewController: NSTouchBarDelegate { // The system calls this while constructing the NSTouchBar for each NSTouchBarItem you want to create. func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {     switch identifier {     case button:         let buttonItem = NSButtonTouchBarItem(identifier: identifier)         buttonItem.title = NSLocalizedString("Button", comment: "")         buttonItem.target = self         buttonItem.action = #selector(buttonAction)         buttonItem.image = NSImage(systemSymbolName: "tray", accessibilityDescription: "tray")         return buttonItem     default:         return nil     } } } #endif
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Touch Bar
I have written some code in a separate file which is shown below. I don't know whether this code works or not because when I run my app on Mac, nothing appears on my Touch Bar. I am sure I need to call the class somewhere within my app but I don't know where. Any thought on this would be much appreciated. Many thanks. #if targetEnvironment(macCatalyst) import Cocoa class TouchBarViewController: NSViewController {     let button = NSTouchBarItem.Identifier("com.TouchBarCatalog.TouchBarItem.button")     let buttonBar = NSTouchBar.CustomizationIdentifier("com.TouchBarCatalog.buttonBar")     @IBOutlet weak var HelpButton: NSButton!     @IBOutlet weak var PhotosButton: NSButton!     @IBOutlet weak var CameraButton: NSButton!     @IBOutlet weak var HistoryButton: NSButton!     @IBOutlet weak var SettingsButton: NSButton! } // MARK: - Action Functions override func viewDidLoad() {     super.viewDidLoad() } override func makeTouchBar() -> NSTouchBar? {     let touchBar = NSTouchBar()     touchBar.delegate = self     touchBar.customizationIdentifier = buttonBar     touchBar.defaultItemIdentifiers = [button]     return touchBar } @IBAction func customize(_ sender: AnyObject) {     guard let touchBar = touchBar else { return }     for itemIdentifier in touchBar.itemIdentifiers {         guard let item = touchBar.item(forIdentifier: itemIdentifier) as? NSButtonTouchBarItem,             let button = item.view as? NSButton else { continue }         button.bezelColor = useCustomColor.state == NSControl.StateValue.on ? NSColor.systemYellow : nil     } } @IBAction func buttonAction(_ sender: AnyObject) {     if let button = sender as? NSButtonTouchBarItem {         print("\(#function): button with title \"\(button.title)\" is tapped")     } } } // MARK: - NSTouchBarDelegate extension TouchBarViewController: NSTouchBarDelegate { // The system calls this while constructing the NSTouchBar for each NSTouchBarItem you want to create. func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {     switch identifier {     case button:         let buttonItem = NSButtonTouchBarItem(identifier: identifier)         buttonItem.title = NSLocalizedString("Button", comment: "")         buttonItem.target = self         buttonItem.action = #selector(buttonAction)         buttonItem.image = NSImage(systemSymbolName: "tray", accessibilityDescription: "tray")         return buttonItem     default:         return nil     } } } #endif
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Integrating the Touch Bar into an iOS and MacOS app.
I have updated the code for my Touch Bar as shown below. My app successfully runs on iPhone and iPad however on Mac, it fails to run and produces the errors shown in my screenshot. Any thoughts on how to fix this would be great. Many thanks. import UIKit #if targetEnvironment(macCatalyst) extension NSTouchBarItem.Identifier {     static let deleteRecipe = NSTouchBarItem.Identifier("com.example.apple-samplecode.Recipes.deleteRecipe")     static let editRecipe = NSTouchBarItem.Identifier("com.example.apple-samplecode.Recipes.editRecipe")     static let toggleRecipeIsFavorite = NSTouchBarItem.Identifier("com.example.apple-samplecode.Recipes.toggleRecipeIsFavorite") } extension ViewController2: NSTouchBarDelegate {     override func makeTouchBar() -> NSTouchBar? {         let touchBar = NSTouchBar()         touchBar.delegate = self         touchBar.defaultItemIdentifiers = [             .flexibleSpace,             .deleteRecipe,             .flexibleSpace,             .editRecipe,             .toggleRecipeIsFavorite,             .flexibleSpace         ]         return touchBar     }     func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {         let touchBarItem: NSTouchBarItem?         switch identifier { //        case .deleteRecipe: //            guard let image = UIImage(systemName: "trash") else { return nil } //            touchBarItem = NSButtonTouchBarItem(identifier: identifier, //                                                image: image, //                                                target: self, //                                                action: #selector(RecipeDetailViewController.deleteRecipe(_:))) //         case .editRecipe:             guard let image = UIImage(systemName: "square.and.pencil") else { return nil }             touchBarItem = NSButtonTouchBarItem(identifier: identifier,                                                 image: image,                                                 target: self,                                                 action: #selector(abc(_:))) //        case .toggleRecipeIsFavorite: //            guard let recipe = self.recipe else { return nil } // //            let name = recipe.isFavorite ? "heart.fill" : "heart" //            guard let image = UIImage(systemName: name) else { return nil } // //            touchBarItem = NSButtonTouchBarItem(identifier: identifier, //                                                image: image, //                                                target: self, //                                                action: #selector(RecipeDetailViewController.toggleFavorite(_:)))         default:             touchBarItem = nil         }         return touchBarItem     } } // Action on 'Photos' tab: struct abc: View {     var body: some View {         storyboardview2().edgesIgnoringSafeArea(.all) // ViewController2 (Photos page)     } } #endif
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Saving the text inside a UITextView to iCloud.
Below I have attached the code for the text extraction. The extracted text is saved in the UITextView and it is this which I want stored on iCloud using the code from the previous post. Many thanks for your help. import SwiftUI import UIKit import Vision class ViewController2: UIViewController {     let stackView: UIStackView = {         let stack = UIStackView()         stack.axis = .vertical         stack.alignment = .center         stack.spacing = 20         return stack     }()     @IBOutlet weak var imageView: UIImageView!     @IBOutlet weak var textView: UITextView!     @IBOutlet weak var activityIndicator: UIActivityIndicatorView!     @IBOutlet weak var button: UIButton!     @IBOutlet weak var shareButton: UIButton!     override func viewDidLoad() {         super.viewDidLoad()         //setupUI()         button.backgroundColor = .systemCyan // Background colour of the select photo button         button.setTitle("Select Photo", for: .normal) // Button text         button.setTitleColor(.white, for: .normal) // Button text Colour         // Rounding the edges of the 'Select Photo' button:         button.layer.cornerRadius = 25         button.layer.borderWidth = 20         button.layer.borderColor = UIColor.systemCyan.cgColor         // Rounding the edges of the 'Share' button:         shareButton.layer.cornerRadius = 25         shareButton.layer.borderWidth = 10         shareButton.layer.borderColor = UIColor.systemCyan.cgColor         stopAnimating() // Activity indicator disappears     }     // Defining the activity indicators show and spin     private func startAnimating() {         self.activityIndicator.startAnimating()     }     // Defining the activity indicators stop and hide     private func stopAnimating(){         self.activityIndicator.stopAnimating()     }     @IBAction func selectPhotoButton(_ sender: Any) { // When selectPhoto button is pressed,         SelectPhotoButtonPressed() // run the function SelectPhotoButtonPressed.     }     private func SelectPhotoButtonPressed(){         if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){             let imageSelector = UIImagePickerController() // Apple's interface for taking pictures and loading items from camera roll             imageSelector.sourceType = .photoLibrary // Opens the device's photo library             imageSelector.delegate = self // Leaves the UIImagePickerController when a picture is selected             self.present(imageSelector, animated: true, completion: nil) // Present the imageSelector          }     }     // Text Recognition     // Create request     var request = VNRecognizeTextRequest(completionHandler: nil)     private func VisionOCR(image: UIImage?){         var textString = "" // Variable textString = string         // Create completion handler         request = VNRecognizeTextRequest(completionHandler: { (request, error)in  // Locates all the text in the image.             // Results are in the request             guard let results = request.results as?[VNRecognizedTextObservation] else {fatalError("Recieved Invalid Observation")}             for visionResult in results{                 guard let recognisedText = visionResult.topCandidates(1).first else{ // Text stored in chronological order.                     print("No text")                     continue                 }                 textString += "\n\(recognisedText.string)"                 DispatchQueue.main.async{ // FIFO queue                     self.stopAnimating() // Hide the activityIndicator                     self.textView.text = textString // Assign the textView the recoginsed text                 }             }         })         // Properties         request.minimumTextHeight = 0.03125 // Default mimnimum height for text to be recognised in comparison to image, (1/32).         request.recognitionLevel = .accurate // Choice between accurate and fast.         request.recognitionLanguages = ["en_UK", "en-US", "fr-FR", "it-IT", "de-DE", "es-ES", "pt-BR", "zh-Hans", "zh-Hant", "yue-Hans", "yue-Hant", "ko-KR", "ja-JP", "ru-RU", "uk-UA"] // Recognisable languages.         request.usesLanguageCorrection = true // Applies language correction.         let requests = [request]         // Request handler         DispatchQueue.global(qos: .userInitiated).async{  // FIFO queue, qos (quality of service) determines priotity for scheduling tasks             guard let img = image?.cgImage else {fatalError("Missing image to scan")} // Variable image = computer generated image             // Create request handler             let requestHandler = VNImageRequestHandler(cgImage: img, options: [:])  // Performs Vision requests             // Send request to request handler             try? requestHandler.perform(requests) // Schedules Vision requests to be performed         }     } } extension ViewController2: UIImagePickerControllerDelegate, UINavigationControllerDelegate{     func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey :Any]){         picker.dismiss(animated: true, completion: nil)         startAnimating()         self.textView.text = ""         let image = info[UIImagePickerController.InfoKey.originalImage]as?UIImage         self.imageView.image = image         VisionOCR(image: image)     } } public struct storyboardview2: UIViewControllerRepresentable{     public func makeUIViewController(context content: Context) -> UIViewController {         let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)         let controller = storyboard.instantiateViewController(identifier: "selectPhoto")         return controller     }     public func updateUIViewController(_ uiViewController: UIViewController, context: Context) {     } }
Topic: UI Frameworks SubTopic: UIKit Tags:
Dec ’22
Reply to Touch Bar
I have updated the code for my Touch Bar as shown below. My app successfully runs on iPhone and iPad however on Mac, it fails to run and produces the errors shown in my screenshot. Any thoughts on how to fix this would be great. Many thanks. import UIKit #if targetEnvironment(macCatalyst) extension NSTouchBarItem.Identifier {     static let deleteRecipe = NSTouchBarItem.Identifier("com.example.apple-samplecode.Recipes.deleteRecipe")     static let editRecipe = NSTouchBarItem.Identifier("com.example.apple-samplecode.Recipes.editRecipe")     static let toggleRecipeIsFavorite = NSTouchBarItem.Identifier("com.example.apple-samplecode.Recipes.toggleRecipeIsFavorite") } extension ViewController2: NSTouchBarDelegate {     override func makeTouchBar() -> NSTouchBar? {         let touchBar = NSTouchBar()         touchBar.delegate = self         touchBar.defaultItemIdentifiers = [             .flexibleSpace,             .deleteRecipe,             .flexibleSpace,             .editRecipe,             .toggleRecipeIsFavorite,             .flexibleSpace         ]         return touchBar     }     func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {         let touchBarItem: NSTouchBarItem?         switch identifier { //        case .deleteRecipe: //            guard let image = UIImage(systemName: "trash") else { return nil } //            touchBarItem = NSButtonTouchBarItem(identifier: identifier, //                                                image: image, //                                                target: self, //                                                action: #selector(RecipeDetailViewController.deleteRecipe(_:))) //         case .editRecipe:             guard let image = UIImage(systemName: "square.and.pencil") else { return nil }             touchBarItem = NSButtonTouchBarItem(identifier: identifier,                                                 image: image,                                                 target: self,                                                 action: #selector(abc(_:))) //        case .toggleRecipeIsFavorite: //            guard let recipe = self.recipe else { return nil } // //            let name = recipe.isFavorite ? "heart.fill" : "heart" //            guard let image = UIImage(systemName: name) else { return nil } // //            touchBarItem = NSButtonTouchBarItem(identifier: identifier, //                                                image: image, //                                                target: self, //                                                action: #selector(RecipeDetailViewController.toggleFavorite(_:)))         default:             touchBarItem = nil         }         return touchBarItem     } } // Action on 'Photos' tab: struct abc: View {     var body: some View {         storyboardview2().edgesIgnoringSafeArea(.all) // ViewController2 (Photos page)     } } #endif
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22