【发布时间】:2011-03-27 15:53:36
【问题描述】:
我想在呈现 modalView 时将数据(字符串数组)从父视图加载到子视图中的一组 UITextField 中。
我知道如何从子代传给父代,而且我敢肯定它更容易走另一条路,但我不知道如何。
更新:因为我发现问题而删除了更新(模态视图的双重释放)
【问题讨论】:
标签: ios objective-c iphone parent-child pass-data
我想在呈现 modalView 时将数据(字符串数组)从父视图加载到子视图中的一组 UITextField 中。
我知道如何从子代传给父代,而且我敢肯定它更容易走另一条路,但我不知道如何。
更新:因为我发现问题而删除了更新(模态视图的双重释放)
【问题讨论】:
标签: ios objective-c iphone parent-child pass-data
如果你想变得非常花哨,你可以为你的子视图创建一个委托。
@protocol MyChildViewDelegate
- (NSArray*)getStringsForMyChildView:(MyChildView*)childView;
@end
@interface MyChildView : UIView
{
id <MyChildViewDelegate> delegate;
...
}
@property (nonatomic, assign) id <MyChildViewDelegate> delegate;
...
@end
然后在你的视图中的某个地方你会要求字符串:
- (void)viewDidLoad
{
...
NSArray* strings = [delegate getStringsForMyChildView:self];
...
}
然后在你的控制器中(或任何地方)你可以这样做:
myChildView = [[MyChildView alloc] initWith....];
myChildView.delegate = self;
...
- (NSArray*)getStringsForMyChildView:(MyChildView*)childView
{
return [NSArray arrayWithObjects:@"one", @"two", @"three", nil];
}
在这种情况下可能有点矫枉过正,但这也是 UITableView 的做法:它们有一个数据源委托来为它们提供内容。
【讨论】:
- (id)initWithDataObject:(YourDataObjectClass *)dataObject {
if (self = [super init]) {
self.dataObject = dataObject;
// now you can do stuff like: self.myString = self.dataObject.someString;
// you could do stuff like that here or if it is related to view-stuff in viewDidLoad
}
return self;
}
【讨论】:
两种方法:
1.按照 Matt 的建议重写 init 方法
2.在您的子类中创建字段并将这些值传递给您的文本字段。
@interface ChildViewController : UIViewController{
NSArray *strings;
UITextfield *textField1;
UITextfield *textField2;
}
...
- (void)viewDidLoad {
[super viewDidLoad];
textField1.text = [strings objectAtIndex:0];
textField2.text = [strings objectAtIndex:1];
}
然后在父类中:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
ChildViewController *childController = [[ChildViewController alloc] init];
childController.strings = your_array_of_strings;
[self.navigationController pushViewController:childController animated:YES];
[childController release];
}
【讨论】:
覆盖子视图控制器的 init 方法。
- (id) initWithStrings:(NSArray *)string {
if (self = [super init]) {
// Do stuff....
}
return self;
}
然后在父级中:
MyChildViewController *vc = [[[MyChildViewController alloc] initWithStrings: strings] autorelease];
【讨论】: