重新加载子视图目标C



我有这样的代码,它根据在表视图中选择的选项将a子视图设置为某个ViewController的视图。这是代码:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self setMainView:[[[self controllerArray] objectAtIndex:[indexPath row]] view]];
    [self setCurrentViewController:[indexPath row]];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

最初添加子视图的代码如下所示:

[self setMainView:[[[self controllerArray] objectAtIndex:0] view]];
[[self view] addSubview:[self mainView]]

问题是,更改子视图的代码不会更新子视图,因此视图永远不会实际加载。我可以通过从子视图([[self mainView] removeFromSuperview])中删除视图来重新加载视图,但这会导致它重新加载到中心。子视图可以根据用户的手势移动,我想把它放在同一个地方。有没有办法重新加载子视图,或者我必须跟踪子视图的位置,然后在删除并再次添加后设置它。

编辑:一个有趣的提示:这个代码工作得很好(视图停留在上一个坐标):

[[self mainView] removeFromSuperview];
[self setMainView:[[[self controllerArray] objectAtIndex:[indexPath row]] view]];
[[self view] addSubview:[self mainView]];
[self setCurrentViewController:[indexPath row]];
[tableView deselectRowAtIndexPath:indexPath animated:YES];

除了第一次切换视图之外。我可以设置一次坐标,但有没有更快的方法,所以我不必每次切换时都删除和添加视图。

这能解决问题吗?

[[self mainView] removeFromSuperview];
[self setMainView:[[[self controllerArray] objectAtIndex:[indexPath row]] view]];
[self addSubview:[self mainView]];
[self setCurrentViewController:[indexPath row]];
[tableView deselectRowAtIndexPath:indexPath animated:YES];

第1版:如果这只是您想要重置的位置,您可以添加属性CGRect originalFrame,并在添加子视图的代码中添加:

[self setMainView:[[[self controllerArray] objectAtIndex:0] view]];
[[self view] addSubview:[self mainView]];
self.originalFrame = [self mainView].frame;

然后当你想重置位置时,使用:

[[self mainView] setFrame:self.originalFrame];

第2版:也许使用视图的"隐藏"属性就足够了?这样你就可以一次把它们都作为子视图,但只让一个可见,比如这个

[self mainView].hidden = YES;
[self setMainView:[[[self controllerArray] objectAtIndex:[indexPath row]] view]];
[self mainView].hidden = NO;
[self setCurrentViewController:[indexPath row]];
[tableView deselectRowAtIndexPath:indexPath animated:YES];

请记住在开始时添加所有子视图,并将其隐藏设置为YES,但首先要显示的视图除外。

最新更新