Mit*_*ell 3 cocoa-touch objective-c uitableview uikit ios
I have UITableView which uses a custom UITableViewCell containing a UITextField.
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];
Run Code Online (Sandbox Code Playgroud)
When the UITextField is clicked, nothing happens.
I attempted to do the exact same thing for another UITextField outside of the UITableView:
[othertf addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventTouchDown];
Run Code Online (Sandbox Code Playgroud)
When I click on othertf the method is called as I would expect.
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;
}
Run Code Online (Sandbox Code Playgroud)
谁能发现我做错了什么?这可能是一件简单的事情,因为我是iOS开发的新手.
使用UITextField delegate方法:
//Use this method insted of addTarget:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if (textField == tf) {
[self myMethod];
return NO;
}
return YES;
}
Run Code Online (Sandbox Code Playgroud)
并且不要忘记将委托设置为textField:
tf.delegate = self;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8817 次 |
| 最近记录: |