问题描述
我有 UITableView
它使用自定义 UITableViewCell
包含 UITextField
。
I have UITableView
which uses a custom UITableViewCell
containing a UITextField
.
我想在单击时调用一个方法( myMethod
)( UIControlEventTouchDown
)并通过执行以下操作尝试在 UITableView
委托方法 cellForRowAtIndexPath
I want to call a method (myMethod
) when it is clicked (UIControlEventTouchDown
) and attempted to wire this up inside the UITableView
delegate method cellForRowAtIndexPath
by doing the following:
[tf addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventTouchDown];
当点击 UITextField
。
我试图对另一个 UITextField
做同样的事情 UITableView
:
I attempted to do the exact same thing for another UITextField
outside of the UITableView
:
[othertf addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventTouchDown];
当我点击 othertf
调用,我会期望。
When I click on othertf
the method is called as I would expect.
我有点困惑,因为代码是相同的,除了我交换 tf
为 othertf
。
I'm a bit confused as the code is identical apart from I've swapped tf
for 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开发。
Can anyone spot what I'm doing wrong? It's probably something simple as I am new to iOS development.
推荐答案
使用 UITextField
委托
方法:
//Use this method insted of addTarget:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if (textField == tf) {
[self myMethod];
}
}
并且不要忘记将委托设置为textField:
and dont forget to set the delegate to the textField:
tf.delegate = self;
这篇关于iOS - 为UITextField在自定义UITableViewCell内添加目标/操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!