Swift:在 TableView 中获取 TextView 的文本(可能有两种方法)

Swift: get text of TextView inside TableView (two approaches possible)

我有一个 TableView,其中包含可编辑的 TextView,我想在用户尝试移至下一页时检查它们是否包含文本。但是我不确定如何从 TableView 中引用它们。有什么想法吗?

这是我的设置:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "ActionCell", for: indexPath) as! StepCell

    // Cell Formatting

    cell.label.delegate = self
    cell.delegate = self

    return cell
}

然后是 textview 委托的扩展:

extension Step3: UITextViewDelegate {


func textViewDidChange(_ textView: UITextView) {
    let cell = textView.superview?.superview as? StepCell
    let indexPath = tableview.indexPath(for: cell!)
    goals[goals.count - 1].steps![indexPath!.row].title = textView.text
    resizeTableViewCell()
}

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" || text == "\t" {
        textView.resignFirstResponder()
        return false
    }
    return true
    }
}

在我的 viewcontroller 中有一个按钮,如果所有字段都有文本,该按钮将前进到下一页。

每次创建 Goal 对象时,每个步骤都会添加空文本,因此我考虑检查数组以查看对象是否有任何文本,但这是另一个数组中的数组,我不能让它工作。我尝试了类似下面的操作,但我收到一条错误消息,提示类型 'Goal' 不符合协议 'Sequence'

@IBAction func nextTU(_ sender: Any) {

    for steps in goals[0] {
        print(steps.steps)
}

如果它很重要,这里是添加一个步骤的代码:

@IBAction func addTU(_ sender: Any) {
    goals[goals.count - 1].steps?.append(Step(title: ""))
}

目标的结构如下所示:

struct Goal: Codable, Equatable {
    var title: String
    var description: String?
    var duration: String
    var steps: [Step]?
    var completedSteps: [Step]?
    var completed: Bool
    var dateCreated: Date

    func returnYear(date: Date) -> Int {
        let calendar = Calendar.current
        return calendar.component(.year, from: date)
    }
}

Step 的那个是这样的:

struct Step: Codable, Equatable {
    var title: String
}

总而言之,我需要检查 TableView 中所有 textView 的文本,或者遍历数组中的数组。

有什么想法吗?

谢谢

goals[0] 是一个 Goal 类型的对象你不能遍历它,你需要

@IBAction func nextTU(_ sender: Any) { 
   for step in goals.last!.steps {
       if step.text == "" {
          // alert user 
       }
   }
}

goals.last?.steps!.forEach { 
    if [=11=].title == "" {
       print("I'm empty!") 
    } 
}

上面你应该使用 goals.last!.steps 在这里 goals[goals.count - 1] 你将所有值设置为数组中的最后一项