關(guān)于cell中textField值回傳有很多辦法,代理啊,block啊,都可以實(shí)現(xiàn)。
不過今天我給大家講一個(gè)我自己想出來的方法。
我寫了個(gè)小demo,里面什么都沒有,不過基本原理還是可以看出來的。
代碼非常簡單,在viewController中只需要在返回cell的方法里面把接受這個(gè)數(shù)據(jù)的一個(gè)數(shù)組和所在的indexPath傳進(jìn)去就可以,代碼:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
TextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
cell.data = _data;
cell.indexPath = indexPath;
return cell;
}
在cell.h 中需要定義兩個(gè)屬性接收,
#import <UIKit/UIKit.h>
#define kIndexPath @"indexPath"
#define kText @"text"
@interface TextFieldCell : UITableViewCell
@property (nonatomic, strong) NSMutableArray *data;
@property (nonatomic, strong) NSIndexPath *indexPath;
@end
只需要在cell的textfield中改變內(nèi)容的方法中這么寫就可以了:
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:_indexPath forKey:kIndexPath];
[dic setValue:textField.text forKey:kText];
[textField endEditing:YES];
[_data addObject:dic];
return YES;
大家注意:在view controller中傳的是一個(gè)數(shù)組的地址指針。就是說如果在cell里面添加了元素,在view controller中也會(huì)添加,因?yàn)椴皇莻鬟^去的[_data copy],所以還是一個(gè)數(shù)組,這樣就在viewController中同時(shí)變化。這樣就實(shí)現(xiàn)了view controller和cell中數(shù)據(jù)同步的問題。
這樣寫首先代碼非常簡潔,邏輯非常清晰,可移植性好,如果別的view controller想用這個(gè)cell那么只需要把indexPath和數(shù)據(jù)源傳過去就可以了,其余的根本不用考慮。最重要的是有的時(shí)候別人想不明白指針的應(yīng)用,這樣你就可以裝逼了。。。