获取按钮的文本字段值单击表视图

时间:2017-09-16 04:22:32

标签: ios objective-c uitableview uitextfield

我正在开发IOS Application.to在TableViewCell中点击按钮获取文本字段值。我可以得到按钮的索引并传递给TableViewCell,然后将单元格传递给textfield.and从textfield获取文本以获取(Null)文本。但是问题。请提前帮助谢谢。

//Tableviewcell create textfield

_quantity = [[UITextField alloc]initWithFrame:CGRectMake(770.0f, 10.0f,80.0f, 30.0f)];
[_quantity setFont:[UIFont systemFontOfSize:15.0f]];
_quantity.delegate =self;
[_quantity.layer setBorderColor: [[UIColor blackColor] CGColor]];
[_quantity.layer setBorderWidth: 1.0];
_quantity.textAlignment =  NSTextAlignmentCenter;
_quantity.tag = indexPath.row;
_quantity.text = obj.productQuantity;
_quantity.leftViewMode = UITextFieldViewModeAlways;
[_quantity setAdjustsFontSizeToFitWidth:YES];
[cell addSubview:_quantity];

_quantitySave = [[UIButton alloc]initWithFrame:CGRectMake(770.0f, 45.0f,80.0f, 20.0f)];
_quantitySave.tag = indexPath.row;
[_quantitySave.layer setCornerRadius:4.0f];
[_quantitySave.layer setBorderColor: [[UIColor blackColor] CGColor]];
[_quantitySave.layer setBorderWidth: 1.0];
_quantitySave.tintColor = [UIColor blackColor];
[_quantitySave setTitle:@"Delete" forState:UIControlStateNormal];
[_quantitySave addTarget:self action:@selector(saveQuantity:) forControlEvents:UIControlEventTouchDown];
[cell addSubview:_quantitySave];

-(IBAction)saveQuantity:(id)sender{
    UIButton *button = (UIButton*)sender;
    NSInteger index = button.tag;

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    UITextField *textField = (UITextField *)[cell viewWithTag:index];
    NSLog(@"%@",textField.text);
}

2 个答案:

答案 0 :(得分:1)

您正在UITextField中添加_quantity.tag = indexPath.row;标记,并从button.tag获取您尚未设置的索引。您应该在按钮中添加tag

_quantity = [[UITextField alloc]initWithFrame:CGRectMake(770.0f, 10.0f,80.0f, 30.0f)];
    [_quantity setFont:[UIFont systemFontOfSize:15.0f]];
    _quantity.delegate =self;
    [_quantity.layer setBorderColor: [[UIColor blackColor] CGColor]];
    [_quantity.layer setBorderWidth: 1.0];
    _quantity.textAlignment =  NSTextAlignmentCenter;
    //_quantity.tag = indexPath.row;
    yourButtonObject.tag = indexPath.row
    _quantity.text = obj.productQuantity;
    _quantity.leftViewMode = UITextFieldViewModeAlways;
    [_quantity setAdjustsFontSizeToFitWidth:YES];
    [cell addSubview:_quantity];


-(IBAction)saveQuantity:(id)sender{
 UIButton *button = (UIButton*)sender;
 NSInteger index = button.tag;

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
UITextField *textField = (UITextField *)[cell viewWithTag:index];
 NSLog(@"%@",textField.text);

答案 1 :(得分:0)

要以更优雅的方式创建可编辑的UITableViewCell,请检查以下图像,这将为您提供创建TableView单元格所需的所有代码,以响应完成的操作并打印所选单元格的文本字段文本。

enter image description here

一旦我弄清楚为什么我的git帐户无效,我会添加代码。