loading...

Vocabulary Words

casualty profile image Thomas Dye ・1 min read

Swift Vocabulary

SwiftVocabulary

Click on a cell to segue to it's Definition View Controller

Click Add Word at the bottom to submit a word, definition, and example

Swipe left to delete a cell




Let's make an example struct

struct VocabularyWord {
    let word: String
    let definition: String
    let example: String
}

Now let's make an array using the VocabularyWord type

    var vocabWords: [VocabularyWord] = [VocabularyWord(word: "word1", definition: "definition1", example: "example1"), VocabularyWord(word: "word2", definition: "definition2", example: "example2")]

Now we need to add them to their cells

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return vocabWords.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ReuseIdentifier", for: indexPath)

        let word = vocabWords[indexPath.row]
        cell.textLabel?.text = word.word
        return cell
    }

Now we can make the link from the cell to the Definition View

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == NameOfSegueHere" {

            guard let indexPath = tableView.indexPathForSelectedRow,
                let definitionVC = segue.destination as? ViewControllerNameHere else { return }

            let cellWord = vocabWords[indexPath.row]

            definitionVC.cellWord = cellWord

        }
    }

We can also add this cool feature to delete unwanted items

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {
            vocabWords.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
        }

    }

Posted on by:

Discussion

pic
Editor guide