7

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

cellForRowAtIndexPath将返回零。

4

5 回答 5

17

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

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell dealloc]
}
于 2014-05-23T23:50:21.513 回答
1

UITableViewCells离开可视区域时,UITableView它实际上已从tableview中删除并放回重用队列中。如果它被选中用于重用,它将由dequeueReusableCellWithIdentifier:.

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

你最终想要做什么?

于 2013-08-07T03:33:30.107 回答
1

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

AUITableViewCell是一个视图,根据MVC Pattern。因此,如果我是您,我更愿意维护一个模型对象——也许它就像一个NSString实例一样简单——将文本保存在单元格中。您可以通过向控制器添加 keyUITextField观察者来观察 的变化。UITextFieldTextDidChangeNotification

- (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

于 2013-08-07T03:52:30.407 回答
0

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

于 2013-08-07T03:43:42.410 回答
-3

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

看起来像:

。H

UITextField *textfiled;

.m

-(void)viewDidLoad
{
    //init textfield
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //init cell...

    [cell addSubview:textfield];
    return cell;
}
于 2013-08-07T03:24:19.967 回答