这可以在 Objective-C 运行时中为任何实例(不必是 UITextField)以及任何关联对象(不必是 NSIndexPath)完成。
对于这个问题,我们可以创建一个类别UIView+RepresentingIndexPath。
我们的接口允许我们设置和检索一个 NSIndexPath:
@interface UIView (RepresentingIndexPath)
- (void)representIndexPath:(NSIndexPath *)indexPath;
- (NSIndexPath *)representedIndexPath;
@end
我们的实现使用 Objective-C 关联对象来设置和检索视图上的索引路径:
#import "UIView+RepresentingIndexPath.h"
#import <objc/runtime.h>
static char IndexPathKey;
@implementation UIView (RepresentingIndexPath)
- (void)representIndexPath:(NSIndexPath *)indexPath
{
objc_setAssociatedObject(self, &IndexPathKey, indexPath, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSIndexPath *)representedIndexPath
{
return objc_getAssociatedObject(self, &IndexPathKey);
}
@end
在行动:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TextFieldTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TextFieldCell" forIndexPath:indexPath];
[cell.textField addTarget:self action:@selector(textFieldTextChanged:) forControlEvents:UIControlEventEditingChanged];
[cell.textField representIndexPath:indexPath];
return cell;
}
- (void)textFieldTextChanged:(UITextField *)sender
{
NSIndexPath *indexPath = [sender representedIndexPath];
NSLog(@"%@", indexPath);
}
?
最后一点!如果您可以在不这样做的情况下实现您想要做的事情,那么真的应该避免在运行时乱搞。只是想我会添加另一个解决方案!