- 在Tableview 中添加UItextField控件,并且给每一UItextfield添加事件,并且将方法设置在编辑结束的时候触发,这样就可以捕捉到填写在UItextfield上的内容
#pragma mark - 初始化tableview的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = [indexPath row];
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text = [self.xinxi objectAtIndex:row]; //给每一行添加标题
cell.textLabel.font = [UIFont systemFontOfSize:15];
CGRect textFieldRect = CGRectMake(0.0, 0.0f, 215.0f, 31.0f);
UITextField *theTextField = [[UITextField alloc] initWithFrame:textFieldRect];
theTextField.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
theTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
theTextField.returnKeyType = UIReturnKeyDone;
theTextField.clearButtonMode = YES;
theTextField.tag = row;
theTextField.delegate = self; //将代理指向自己
//给每一个UITextField添加事件,使得编辑结束时调用textFieldWithText方法
[theTextField addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
switch (row) {
case 0:
theTextField.placeholder = @"请填写第一行";
theTextField.returnKeyType = UIReturnKeyDefault;
break;
case 1:
theTextField.placeholder = @"请填写第二行";
theTextField.returnKeyType = UIReturnKeyDefault;
break;
case 2:
theTextField.placeholder = @"请填写第三行";
theTextField.returnKeyType = UIReturnKeyDefault;
break;
default:
break;
}
cell.accessoryView = theTextField;
return cell;
}
#pragma mark - 获取每个UITextField在编辑结束的值
- (void)textFieldWithText:(UITextField *)textField
{
switch (textField.tag) {
case 0:
_theOneRow = textField.text;
break;
case 1:
_theTwoRow = textField.text;
break;
case 2:
_theThreeRow = textField.text;
break;
default:
break;
}
}
当然除了给每一个UItextfield设置事件之外,还可以给每一个UItextfield设置tag值,然后通过tag值找到那个UItextfield控件,并把它text的值读取出来的,如果是一进入页面就要显示内容,也可以通过tag值进行设置。
2.编辑结束后如何隐藏键盘。隐藏键盘有很多方法,比如点击不可填写内容的区域来隐藏键盘,也可以使用键盘上的return按钮进行键盘的隐藏。
#pragma mark - 将键盘收起方法一 (编辑结束点击其他地方收起)
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
#pragma mark - 将键盘收起方法二(点击键盘的return按钮收起键盘)
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
3.如何把多余的表格线去除。在初始化了一个表格之后,如果填充的数据较少,只有一两条的话,那么页面会有很多的分割线,要怎么样把这些线给去除呢?其实只要一步就可以了
self.table.tableFooterView = [[UITableView alloc] init];