开发者

iPhone SDK: How to send a message from a TextField inside a TableCell to the viewController?

My app has a UITextField inside of a table cell. 开发者_C百科The table cell is build inside of a TableController class which is the table delegate as well. The TableController is a instance variable of a ViewController class.

What I'm trying to do is to send a message to the ViewController instance when the user touches inside the TextField.

This is a code snipped from the TableController:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *CellIdentifier = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil) {
                 cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        }

        cell.textLabel.text = @"test";

        UITextField *textField = [[[UITextField alloc] initWithFrame:CGRectMake(1.0, 5.0, 120.0, 25.0)] autorelease];
        textField.text = @"test 2";
        [textField addTarget:self action:@selector(editingStarted) forControlEvents:UIControlEventTouchUpInside];    
        cell.accessoryView = textField;
        return cell;

}

The first problem is that the TableControllers method editingStarted gets never called. The next interesting part will be to send a message to the parent ViewController class.


You could hold a weak reference to your parent view controller... and change the controlEventType to DidBeginEditing...

Should be something like this;

In your UITableViewController:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
.....
[textField addTarget: self action:@selector(editingStarted:) forControlEvents: UIControlEventDidBeginEditing];
....
}

-(void)editingStarted:(id)sender {
if([delegate respondsToSelector: action])
[delegate performSelector: action withObject: (UITextField *)sender.text];
}

-(void)setDelegate:(id)del withSelector:(SEL)sel {
delegate = del;
action = sel;
}

In your viewController:

//ViewController.m

-(void)someMethod {
[tableController setDelegate: self withSelector: @selector(recieve:)];
}

-(void)recieve:(NSString *)textFieldString {
//Do stuff
}

Hope this kinda helps... You should know what to declare in .h file.

~ Natanavra.


  1. Set your controller as a delegate of the text field (make sure to adopt the UITextFieldDelegate protocol).
  2. Add the method

.

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    [self editingStarted];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜