我正在开发一个IOS应用程序。我正在动态创建文本字段和按钮,我希望在按钮点击时获取文本字段的文本,但我收到错误:
[UIView setText:]:无法识别的选择器发送到实例
这是我的代码:
- (IBAction)customFieldAdd:(id)sender{
[_addfieldArray addObject:_field];
x = 10;
y = 10;
for( int i = 0; i < [_addfieldArray count]; i++ ) {
UITextField *copyfield = [[UITextField alloc]initWithFrame:CGRectMake(5.0, x + _field.frame.size.height, 195.0f, 30.0f)];
[copyfield setDelegate:self];
[copyfield setTag:i];
[_filterPossibleValueView addSubview:copyfield];
x = x+_field.frame.size.height+10;
UIButton *copyAddButton = [[UIButton alloc]initWithFrame:CGRectMake(202.0f, y + _addField.frame.size.height, 30.0f, 30.0f)];
[copyAddButton setTag:i];
[copyAddButton addTarget:self action:@selector(customFieldDelete:) forControlEvents:UIControlEventTouchUpInside];
[_filterPossibleValueView addSubview:copyAddButton];
y = y+_addField.frame.size.height+10;
count++;
}
}
- (IBAction)customFieldDelete:(id)sender{
UIButton *button = (UIButton*)sender;
NSInteger index = button.tag;
// [_addfieldArray removeObjectAtIndex:index];
UITextField *field = [_filterPossibleValueView viewWithTag:index];
NSString *myText = field.text;
}
答案 0 :(得分:0)
The default value for the tag
property is 0
,您将该值设置为其中一个文本字段。因此,当您尝试使用tag == 0
获取视图时,它将包含多个带有该标记的视图。
设置标记时应使用偏移量:
[copyfield setTag:kOffset + i];
...
[copyAddButton setTag:kOffset*2 + i]; // note that the button and the text field should not have the same tag either
其中kOffset
的定义(例如)如下:
let kOffset: Int = 1000
然后,要获取文本字段的文本,您可以使用:
NSInteger tag = button.tag - kOffset;
UITextField *field = [_filterPossibleValueView viewWithTag:tag];
NSString *myText = field.text;