Search code examples
iosswiftuipasteboard

Issues with call of UIPasteBoard


I have a problem with my keyboard.

I created a view as input source of my project.

In order to do this I used UIPasteBoard class to write on a textView.

This inputView has a collectionView object that when I press a cell nothing happens.

But, if I copy something, this works good and it write. How can I fix it?

Here my code:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    //Load calculated chord
    let step1 = defaults.string(forKey: "step1") ?? ""
    let step2 = defaults.string(forKey: "step2") ?? ""
    let step3 = defaults.string(forKey: "step3") ?? ""


    switch indexPath.row {
    case indexPath.row:
                cellPressedSound()
                //add selected chord
                // Get a reference to the system pasteboard
                let lPasteBoard = UIPasteboard.general

                // Save the current pasteboard contents so we can restore them later
                let lPasteBoardItems = lPasteBoard.items

                // Update the system pasteboard with my string
                lPasteBoard.string = chromaticScale[indexPath.row] + step1 + step2 + step3

                // Paste the pasteboard contents at current cursor location
                self.chords.paste(self)

                // Restore original pasteboard contents
                lPasteBoard.items = lPasteBoardItems


    default:
        break
    }
}

As I specified before, when I try to write something nothing happens until I don't copy random stuff.


Solution

  • I found the solution by myself. The problem was that I didn't create a clipboard. So to write the selected cell I had to push it twice. So I start by cleaning the iPhone clipboard saving what was copied before in case.

    // Save the current pasteboard contents so we can restore them later
    //let lPasteBoardItems = lPasteBoard.items
    
    //clean clipboard and create path to paste data
    //UIPasteboard.general.string?.removeAll()
    UIPasteboard.general.string = "r"
                                            
    // Get a reference to the system pasteboard
    let lPasteBoard = UIPasteboard.general
                                            
    // Update the system pasteboard adding selected chord
    lPasteBoard.string = chromaticScale[indexPath.row] + step1 + step2 + step3
                                            
    // Paste the pasteboard contents at current cursor location
    self.chords.paste(self)
                        
    // Restore original pasteboard contents
    //lPasteBoard.items = lPasteBoardItems