如何引用驻留在自定义 UITableViewCell 中的 UITextView

How can I reference a UITextView that resides in a custom UITableViewCell

我现在要做的是在我的 cellForRowAtIndexPath 方法中的一个变量中存储对 textView 的引用:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("photoCell") as EditProfileTableViewCell

    cell.imageCaption.tag = indexPath.row
    imageCaptionTextView = cell.imageCaption

    imageCaptionTextView.delegate = self

    return cell

}

然后,当我点击键盘上的完成按钮时,我会尝试访问 textView,当我在其中单击时会显示该按钮。

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

    checkMaxLength(textView, maxLength: 60)

    if text == "\n" {

        imageCaptionTextView.resignFirstResponder()
        return false
    }
    return true
}

我有一些其他代码(未包含在此 post 中)只是在 textView 周围添加了一个边框,以向用户指示已单击 textView。这似乎只适用于第一个 textView .我还向 textView 添加了一个标签并打印到控制台,但标签 returns 相同的数字。

很明显我似乎只引用了第一个单元格。我不能使用 didSelectRow 等,因为此单元格包含一张照片,然后是一个用于为该图像添加标题的 textView。

有没有一些简单的方法来引用我的细胞?我看过有关堆栈溢出的示例,但它们没有包含足够广泛的示例作为答案。

在此希望得到一些帮助。

感谢您的宝贵时间。

假设您的 UITextView 作为子视图添加到单元格的 contentView,那么您可以通过执行以下操作访问封闭的 UITableViewCell

UITableViewCell* cell = (id)textField.superview.superview;

或:

let cell = cell.superview.superview as UITableViewCell?

这依赖于 contentViewUITableViewCell 的子视图的假设,在 iOS 8 之前都是如此,但将来可能不再如此。因此,您可以在那里添加一些检查(例如,使用 isKindOfClass)以确保您获得正确的对象类型。

我认为您可以先获取选定的单元格。 然后,您可以使用您的标签访问它。

NSIndexPath *selectedCellIndex = [self.tableView indexPathForSelectedRow];
UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:selectedCellIndex];

然后,你得到你的目标细胞。因此,您可以使用 tag 来获取 UITextView.

这里link讲一下UIResponder链:https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/event_delivery_responder_chain/event_delivery_responder_chain.html

UITextViewDelegate 具有 textViewDidBeginEditingtextViewDidEndEditing 的功能。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("photoCell") as EditProfileTableViewCell

    cell.imageCaption.tag = indexPath.row
    cell.imageCaption.delegate = self

    return cell
}

func textViewDidBeginEditing(_ textView: UITextView)
{
    textView. // add border here
}

func textViewDidEndEditing(_ textView: UITextView)
{
   textView.text // will give you final value
   textView.tag will give you the row of the cell.
}

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

    checkMaxLength(textView, maxLength: 60)

    if text == "\n" {

        textView.resignFirstResponder()
        return false
    }
    return true
}