Вы захотите создать пользовательский объект UITableViewCell
с протоколом UITextViewDelegate
, чтобы вы могли получить количество слов для конкретного UITableViewCell
UITextView
. Кроме того, вам нужно как-то отправить количество слов на ViewController
, чтобы вы могли обновить количество слов UILabel
. Вы можете достичь этого, создав собственный протокол CustomCellDelegate
, для которого требуется функция updateWordCount()
, а затем использовать этот протокол в своем ViewController
.
Когда количество слов будет обновлено, вы захотите вызвать функцию updateWordCount()
, которая будет находиться в вашем ViewController
с использованием протокола CustomCellDelegate
.
В качестве примера вот что вы хотите сделать:
Создайте файл CustomCell.swift следующим образом:
// Create the protocol
protocol CustomCellDelegate {
func updateWordCount(count: Int)
}
class CustomCell: UITableViewCell, UITextViewDelegate {
// Your UITextView
@IBOutlet weak var textView: UITextView!
// The cells delegate -- which we will set to self when initiated
var delegate: CustomCellDelegate?
func textViewDidChange(_ textView: UITextView) {
// Get the word count here
let wordCount = 10
// Now we call the delegate to send the wordCount to the ViewController
delegate?.updateWordCount(count: wordCount)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
textView.delegate = self
}
}
Теперь создайте пользовательскую ячейку в вашей раскадровке и используйте для нее класс CustomCell
, установив для identifier
значение «CustomCell». Также убедитесь, что вы подключили UITextView
к розетке класса CustomCell
.
Теперь в ViewController
, который содержит UITableView
:
// Use the CustomCellDelegate protocol here
class YourViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CustomCellDelegate {
@IBOutlet weak var wordCountLabel: UILabel!
// This is the function required by the CustomCellDelegate
func updateWordCount(count: Int) {
wordCountLabel.text = "Word Count: \(count)"
}
// Set up the custom Cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
// Setup the delegate
cell.delegate = self
return cell
}
}
Предупреждение: этот код не проверен, и я написал все это в StackOverflow. Могут быть синтаксические ошибки, но кроме нескольких возможных синтаксических ошибок это будет работать.
Edit:
На основании вашего комментария метка подсчета слов находится в ячейке. Это означает, что нам больше не нужен протокол CustomCellDelegate
и мы можем внести некоторые незначительные изменения, чтобы это работало.
CustomCell.swift:
class CustomCell: UITableViewCell, UITextViewDelegate {
// Your UITextView
@IBOutlet weak var textView: UITextView!
// Your Label
@IBOutlet weak var yourLabel: UILabel!
func textViewDidChange(_ textView: UITextView) {
// Get the word count here
let wordCount = 10
// Change the wordCount labels text
yourLabel.text = "Word Count: \(wordCount)"
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
textView.delegate = self
}
}
Убедитесь, что вы используете оба выхода в CustomCell
.
Ваш ViewController
:
class YourViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Set up the custom Cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
return cell
}
}