【问题标题】:UITableViewCell will disappearUITableViewCell 会消失
【发布时间】:2013-08-07 03:16:51
【问题描述】:

我制作了一个 UITableView 并包含了一些自定义 UITableViewCells,在第一个单元格(例如命名为 cell0)中有一些 UITextFields 用于输入,当我滚动 tableView 时,cell0 将从屏幕顶部消失,那么我该如何获取单元格0 中的UITextField 文本?

cellForRowAtIndexPath 将返回 nil。

【问题讨论】:

  • 你需要为每个 textfield 赋予 tag,然后在 didSelectRowAtIndexPath 中获取它的值。
  • @AhmedZ。我只是滚动 tableView 而不是选择单元格。
  • 请展示您的一些代码以便更好地理解

标签: ios uitableview


【解决方案1】:

我发现的唯一方法是 tableview 委托

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell dealloc]
}

【讨论】:

    【解决方案2】:

    根据Apple Documentation about cellForRowAtIndexPath:,它返回“表示表格单元格的对象,如果单元格不可见或 indexPath 超出范围,则返回 nil。”

    根据MVC PatternUITableViewCell 是一个视图。所以我更喜欢维护一个模型对象——如果我是你,它可能就像NSString 实例一样简单——将文本保存在单元格中。您可以通过向控制器添加UITextFieldTextDidChangeNotification 键的观察者来观察UITextField 的变化。

    - (void)textFieldDidChangeText:(NSNotification *)notification
    {
        // Assume your controller has a NSString (copy) property named "text".
        self.text = [(UITextField *)[notification object] text]; // The notification's object property will return the UITextField instance who has posted the notification.
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        // Dequeue cell...
        // ...
        if (!cell)
        {
            // Init cell...
            // ...
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeText:) name:UITextFieldTextDidChangeNotification object:yourTextField];
        }
    
        // Other code...
        // ...
        return cell;
    }
    

    不要忘记删除 -dealloc 中的观察者。

    【讨论】:

      【解决方案3】:

      UITableViewCells 离开UITableView 的可视区域时,它实际上是从tableview 中移除 并放回重用队列中。如果被选中重用,则由dequeueReusableCellWithIdentifier:返回。

      从视图中删除单元格时没有回调。但是,prepareForReuse 会在单元格被 dequeueReusableCellWithIdentifier: 返回之前被调用。

      你最终想要做什么?

      【讨论】:

        【解决方案4】:

        您需要在文本发生更改时将文本保存在某处(例如NSArray)。

        【讨论】:

          【解决方案5】:

          您可以将文本字段初始化为实例变量。

          看起来像:

          .h

          UITextField *textfiled;
          

          .m

          -(void)viewDidLoad
          {
              //init textfield
          }
          
          -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
          {
              //init cell...
          
              [cell addSubview:textfield];
              return cell;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-02-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-07-10
            相关资源
            最近更新 更多