如图所示,为了省事,我将多个textFiled放到了一个cell里,可是随之而来的问题出现了,在获取textFiled.text时竟然为空!!!为此困扰了我好长时间,终于在小伙伴和度娘的帮助下渡过难关。好了,不说废话,直接上代码:
首先在cell.h中我定义了一个block用来将textFiled.text传递出去
#import <UIKit/UIKit.h>
@interface HXHXWantfaqiCell2 : UITableViewCell
@property (weak, nonatomic) IBOutlet UITextField *userNameTextfiled;// 姓名
@property (weak, nonatomic) IBOutlet UITextField *userEmailTextfiled;// 邮箱
@property (weak, nonatomic) IBOutlet UITextField *userPhoneTextfiled;// 电话
@property (weak, nonatomic) IBOutlet UITextField *userCityTextfiled;// 城市
@property (copy,nonatomic) void (^submitApplication)();// 传递提交按钮活动的block
// 重点:这个就是传递textFiled.text的block
@property (copy,nonatomic) void (^textFiledblock)(NSString *str,NSUInteger i);
@end
cell.m中
#import "HXHXWantfaqiCell2.h"
@implementation HXHXWantfaqiCell2
// 提交信息
- (IBAction)btnAction:(id)sender {
if (self.submitApplication) {
self.submitApplication();
}
}
- (void)awakeFromNib {
[super awakeFromNib];
// 在此方法中给每个textFiled设定一个tag
_userNameTextfiled.tag = 101;
// 在此方法中给每个textFiled添加一个方法textFiledAction:
[_userNameTextfiled addTarget:self action:@selector(textFiledAction:) forControlEvents:(UIControlEventEditingChanged)];
_userEmailTextfiled.tag = 102;
[_userEmailTextfiled addTarget:self action:@selector(textFiledAction:) forControlEvents:(UIControlEventEditingChanged)];
_userPhoneTextfiled.tag = 103;
[_userPhoneTextfiled addTarget:self action:@selector(textFiledAction:) forControlEvents:(UIControlEventEditingChanged)];
_userCityTextfiled.tag = 104;
[_userCityTextfiled addTarget:self action:@selector(textFiledAction:) forControlEvents:(UIControlEventEditingChanged)];
}
// 执行此方法
- (void)textFiledAction:(UITextField *)textfile{
self.textFiledblock(textfile.text,textfile.tag);
NSLog(@"%ld-%@",textfile.tag,textfile.text
);
}
@end
在HXWantfaqiVC中引入
#import "HXHXWantfaqiCell2.h"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// 在此方法中对应的cell里写如下代码:
HXHXWantfaqiCell2 *cell = [tableView dequeueReusableCellWithIdentifier:hxCellId2 forIndexPath:indexPath];
// 执行传递textFiled.text的block方法
cell.textFiledblock = ^(NSString *st,NSUInteger tag){
// 根据tag值给相应的NSString字符串赋值
if (tag == 101) {
_name = st;
}if (tag == 102) {
_email = st;
}if (tag == 103) {
_phone = st;
}if (tag == 104) {
_city = st;
}
};
// 提交信息按钮执行方法的block
cell.submitApplication = ^{
// 打印验证结果
NSLog(@"_name = %@\n_email = %@\n_phone = %@\n_city = %@",_name,_email,_phone,_city);
};
return cell;
}