简体   繁体   中英

How to add a new cell to a TableView for each character in a string?

I am trying to take a string from a TextView and add a new row for each character in TextView.text.

so if the TextView text = "hi there" for example, I would like the Table View to look like this:

h

i

(space)

t

h

e

r

e


thank you!

When the user enters new text convert your string into an array of characters:

let chars = Array(string)

Use the array of caracters as the data source for your table view. Call reloadData() on your table view after changing the character array.

Your data source methods might look like this:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return chars.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = String(chars[indexPath.row])
    return cell
}

Edit:

Below is a fully implemented subclass of UITableViewController.

To use it:

  1. Add the class to your project as a Swift file.

  2. Add a UITableViewController scene to your storyboard

  3. Select the "Identity Inspector" and change the class to CharacterTableViewController

  4. Drag a container view onto the view controller that you want to contain your table view. (I'll call this the "parent" view controller)

  5. Control-drag from the container view to your CharacterTableViewController . In the resulting pop-up menu, select "embed" to create an embed segue.

  6. Add a prepare(for:sender:) (prepareForSegue) method to your parent view controller that tries to cast segue.destination to type CharacterTableViewController using an if let and if it succeeds, save the CharacterTableViewController to an instance variable. (Let's call it characterVC .)

  7. Add a text view to your parent view controller. Control drag into your parent view controller to add an IBOutlet to the text view. Call the outlet theTextView .

  8. Add a button to the parent view controller. Control-drag from the button into your parent view controller to create an IBAction. In the button action, fetch the text from theTextView and pass it to characterVC ( characterVC.contentString = theTextView.text )


import UIKit

class CharacterTableViewController: UITableViewController {

    public var contentString: String? {
        didSet {
            if let string = contentString {
                characters = Array(string)
            } else {
                characters = nil
            }
        }
    }

    var characters: [Character]? {
        didSet {
            tableView.reloadData()
        }
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return characters?.count ?? 0
    }

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

        cell.textLabel?.text = String(characters?[indexPath.row] ?? Character(""))
        return cell
    }
}

Edit #2:

I created a project that uses the table view class above in a demo project. You can download it at the following link: https://github.com/DuncanMC/CharacterTableView.git

This one is more directly. Hope you like it.

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return textView.text.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let myText = textView.text
    cell.textLabel?.text = "\(myText[myText.index(myText.startIndex, offsetBy: indexPath.row)])"
    return cell
}

There was a typo. I fixed it and show you the result.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM