【发布时间】:2012-11-14 09:22:23
【问题描述】:
我有UITableView,它使用自定义UITableViewCell,其中包含UITextField。
我想在单击 (UIControlEventTouchDown) 时调用方法 (myMethod) 并尝试通过执行以下操作将其连接到 UITableView 委托方法 cellForRowAtIndexPath 中:
[tf addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventTouchDown];
点击UITextField 时,什么也没有发生。
我试图对UITableView 之外的另一个UITextField 做同样的事情:
[othertf addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventTouchDown];
当我点击othertf 时,该方法会按我的预期调用。
我有点困惑,因为除了将tf 换成othertf 之外,代码是相同的。
下面是cellForRowAtIndexPath的完整代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *DetailCellIdentifier = @"DetailFieldView";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:DetailCellIdentifier];
if (cell == nil) {
NSArray *cellObjects = [[NSBundle mainBundle] loadNibNamed:DetailCellIdentifier owner:self options:nil];
cell = (UITableViewCell*) [cellObjects objectAtIndex:0];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UITextField *tf = (UITextField *)[cell viewWithTag:2];
tf.text = @"some value";
[othertf addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventTouchDown];
[tf addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventTouchDown];
return cell;
}
谁能发现我做错了什么?这可能很简单,因为我是 iOS 开发的新手。
【问题讨论】:
-
是否 UITextField *tf = (UITextField *)[cell viewWithTag:2];给你正确的obj?请检查它是 nil 还是什么
-
是的,因为它采用在第 11 行分配的值 -
tf.text = @"some value";
标签: ios objective-c uitableview cocoa-touch uikit