[英]Getting TextField Text On Button Click
I am developing an IOS App. 我正在开发IOS应用程序。 I am creating a text field and a button dynamically, and I want to get textfield's text on button click, but I'm getting an error:
我正在动态创建一个文本字段和一个按钮,并且我想在单击按钮时获取文本字段的文本,但出现错误:
[UIView setText:]: unrecognized selector sent to instance
[UIView setText:]:无法识别的选择器已发送到实例
Here is my code: 这是我的代码:
- (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;
}
The default value for the tag
property is 0
, and you are setting that value to one of the text fields. tag
属性的默认值为0
,并且您正在将该值设置为文本字段之一。 So, when you try to get the view with tag == 0
, it will have more than one view with that tag. 因此,当您尝试获取
tag == 0
的视图时,它将具有多个使用该标记的视图。
You should use an offset when setting the tag: 设置标签时,应使用偏移量:
[copyfield setTag:kOffset + i];
...
[copyAddButton setTag:kOffset*2 + i]; // note that the button and the text field should not have the same tag either
where kOffset
is defined (for example) like this: 例如,其中定义了
kOffset
:
let kOffset: Int = 1000
Then, to get the text field's text, you can use: 然后,要获取文本字段的文本,可以使用:
NSInteger tag = button.tag - kOffset;
UITextField *field = [_filterPossibleValueView viewWithTag:tag];
NSString *myText = field.text;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.