【发布时间】:2015-10-08 11:10:11
【问题描述】:
有一个UIViewController,由一个UITextField 和一个UITableView 组成。我有一个单独的UIViewTableViewController 子类,用于支持UIViewController(默认)中UITableView 的委托和数据源。我可以从UITexField 获取文本到SecondViewController 并将其保存到NSMutableArray,但这不会传递到UITableView。如果我只是将一个字符串传递给 *cell,它会显示在 UITableView 中。
代码如下:
ViewController.h
#import <UIKit/UIKit.h>
#import "SecondTableViewController.h"
@interface ViewController : UIViewController{
SecondTableViewController *tableController;
}
@end
**ViewController.m**
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
tableController = [[SecondTableViewController alloc] init];
tableController.taskArray = [[NSMutableArray alloc]init];
self.table.dataSource = tableController;
self.table.delegate = tableController;
self.textField.delegate = tableController;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
SecondTableViewController.h
#import <UIKit/UIKit.h>
@interface SecondTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
@property NSMutableArray *taskArray;
@property NSString *taskString;
@end
SecondViewController.m
#import "SecondTableViewController.h"
#import "ViewController.h"
@implementation SecondTableViewController
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
self.taskString = [textField text];
[textField resignFirstResponder];
return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
[self.taskArray addObject:self.taskString];
[textField setText:@""];
NSLog(@"array is %@", self.taskArray);
[self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self
.self.taskArray.count-1 inSection:0]] withRowAnimation:
UITableViewRowAnimationLeft];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.taskArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
cell.textLabel.text = self.taskArray[indexPath.row];
NSLog(@"cell ident %@", self.taskArray[indexPath.row]);
return cell;
}
@end
【问题讨论】:
标签: ios objective-c iphone uitableview uiviewcontroller