单击按钮,将UITextField添加到UITableView

时间:2009-12-15 16:53:44

标签: iphone uitableview uitextfield

经过相当长的一段时间阅读网络后,我决定来这里,因为我通常会在Stack Overflow上超级快速地回答我的问题!

我正在尝试完成以下内容,并会对正确方向的任何建议或指示表示感谢:

  • 显示UITableView
  • 当按下“+”按钮时,UITextField被添加到UITableView的一行
  • 用户可以在此字段中键入字符串
  • 如果用户再次选择“+”按钮,则将另一个UITextfield添加到下一行。 (你明白了)
  • 当用户完成添加UITextField并填写后,可以点击“保存”按钮,此时每行中的所有条目都保存到一个数组中。

对此有任何建议将不胜感激

谢谢!

汤姆

2 个答案:

答案 0 :(得分:1)

这个伪代码可能是一个起点:

// define an NSMutableArray called fields

- (IBAction)addField:(id)sender {
    // create a new text field here and add it to the array
    // then reload data
}

- (IBAction)save:(id)sender {
    for(UITextField *textField in fields) {
        // whatever you have to do
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // you have as many rows as textfields
    return [fields count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    // Set up the cell...
    // For row N, you add the textfield N to the array.
    [cell addSubview:(UITextField *)[fields objectAtIndex:indexPath.row]];
}

答案 1 :(得分:0)

SWIFT 4更新

您可以在此处使用beginUpdate和endUpdate,而不是重新加载整个表。

将目标添加到单元格按钮(可以使用视图标记或创建新的TableviewCell类)。

    cell.addBtn.tag = indexPath.row
    cell.addBtn.addTarget(self, action: #selector(self.addTextField(_:)), for: UIControlEvents.touchUpInside)
    cell.txtField.tag = indexPath.row

然后实现此方法:

@objc func addTextField(_ sender:UIButton) {

    let indexPath = IndexPath(row: sender.tag, section: 0)

    if let cell = tblView.cellForRow(at: indexPath) as? TableCell {
        tblArray.append(cell.txtField.text!)
    }

    let newRow = IndexPath(row: sender.tag + 1, section: 0)
    tblView.beginUpdates()
    tblView.insertRows(at: [newRow], with: .left) 
    tblView.endUpdates()
}

不要忘记将var tblArray:[Any] = [""]放在开头。

希望任何正在寻找Swift答案的人。

快乐的编码。