【发布时间】:2012-09-12 14:54:19
【问题描述】:
您好,我遇到了 UIScrollView 和 ModalViewController 的自动布局问题。
以下是我的编码步骤作为示例代码:
1) 我有一个UIViewController 和一个UIScrollView 作为subView
UIViewController *viewController = [[UIViewController alloc] init];
UIScrollView *scrollView = [[UIScrollView alloc] init];
scrollView.translatesAutoresizingMaskIntoConstraints = NO;
[viewController.view addSubview:scrollView];
UIView *superView = viewController.view;
NSDictionary *viewsDict = NSDictionaryOfVariableBindings(superView,scrollView);
[superView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView(==superView)]|"
options:0
metrics:nil
views:viewsDict]];
[superView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView(==superView)]|"
options:0
metrics:nil
views:viewsDict]];
这行得通
2) 我将 2 个子视图添加到 scrollView
UIView *view1 = [[UIView alloc] init];
view1.backgroundColor = [UIColor redColor];
view1.translatesAutoresizingMaskIntoConstraints = NO;
[scrollView addSubview:view1];
UIView *view2 = [[UIView alloc] init];
view2.backgroundColor = [UIColor greenColor];
view2.translatesAutoresizingMaskIntoConstraints = NO;
[scrollView addSubview:view2];
viewsDict = NSDictionaryOfVariableBindings(scrollView,view1,view2);
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view1(==scrollView)]|"
options:0
metrics:nil
views:viewsDict]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view2(==scrollView)]|"
options:0
metrics:nil
views:viewsDict]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view1(180)][view2(==scrollView)]|"
options:0
metrics:nil
views:viewsDict]];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:@"open" forState:UIControlStateNormal];
btn.frame = CGRectMake(10, 10, 100, 100);
[view2 addSubview:btn];
[btn addTarget:self action:@selector(openPopOver) forControlEvents:UIControlEventTouchUpInside];
这也很好用
3) 我滚动到内容偏移 y 180,我只能看到 view2
[scrollView setContentOffset:CGPointMake(0, 180) animated:YES];
4) 我在 `ViewController 上打开一个 ModalViewController
- (void)openModal{
UIViewController *viewController = [[UIViewController alloc] init];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:@"close" forState:UIControlStateNormal];
btn.frame = CGRectMake(10, 10, 100, 100);
[viewController.view addSubview:btn];
[btn addTarget:self action:@selector(closePopOver) forControlEvents:UIControlEventTouchUpInside];
[self presentViewController:viewController animated:YES completion:nil];
}
5) 当我关闭ModalViewController 我在scrollView 上的布局不起作用时,它会滚动到我尚未设置的不同内容偏移量。当我将内容偏移量重置为 y 180 时,滚动视图的内容大小是错误的。
- (void)closeModal{
[self dismissViewControllerAnimated:YES completion:^{
}];
}
希望有人能帮我解决这个问题。
【问题讨论】:
标签: iphone ios uiscrollview modalviewcontroller autolayout