您将需要使用UITextViewDelegate 协议创建一个自定义UITableViewCell 对象,以便获取特定UITableViewCell UITextView 的字数。此外,您需要以某种方式将字数发送到ViewController,以便您可以更新字数UILabel。您可以通过创建自己的 CustomCellDelegate 协议来实现此目的,该协议需要 updateWordCount() 函数,然后在您的 ViewController 中使用此协议。
当字数统计更新后,您现在需要使用CustomCellDelegate 协议调用位于您的ViewController 中的updateWordCount() 函数。
作为一个例子,这是你想要做的:
如下创建一个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 类中的插座。
现在在包含UITableView 的ViewController 中:
// 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 上。可能存在语法错误,但除了一些潜在的语法错误之外,这将起作用。
编辑:
根据您的评论,字数标签位于单元格中。这意味着我们不再需要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
}
}