iOS 8 AutoLayout 改变视图的位置

Posted

技术标签:

【中文标题】iOS 8 AutoLayout 改变视图的位置【英文标题】:iOS 8 AutoLayout changing the position of a view 【发布时间】:2015-02-07 05:09:58 【问题描述】:

我正在开发一个我最初为 ios 7 制作的应用程序,它运行得非常好,但现在在迁移到 iOS 8 之后,一切都无法正常运行了。基本上,我有一个带有按钮的视图。当我点击该按钮时,另一个带有 UITextField 的 UIView 从可见屏幕区域下方的位置“滑动”到屏幕上。当我点击 UITextField 进行输入时,问题就出现了,此时出现了一个键盘,但带有 UITextField 的视图又回到了它在屏幕外的初始位置。这在 iOS 7 中没有发生,所以我假设这与 iOS 8 的自动布局更改有关。有谁知道我可以做些什么来解决这个问题?如果不需要,我宁愿不关闭自动布局,因为我的应用程序的很大一部分都依赖于它。

这里有一些代码向您展示我所指的内容。在我的示例中,“locationField”是被点击的按钮,“locationView”是滑动到屏幕上的 UIView:

- (IBAction) locationFieldTapped:(UIButton *)sender 
    [self slideViewUp:_locationView];


- (void) slideViewUp:(UIView *)slidingView 
    if (viewIsSlidUp) 
        return;
    

    CGRect frame = slidingView.frame;
    int availableHeight = self.view.frame.size.height;

    // don't move view up if it's already moved up or in the process of moving up
    if (frame.origin.y < availableHeight) 
        return;
    

    viewIsSlidUp = YES;

    // move view just off screen for animation start, in case it's not already there

    frame.origin.y = availableHeight;
    slidingView.frame = frame;

    [UIView animateWithDuration:0.5f animations:^
        CGRect newFrame = frame;
        newFrame.origin.y = availableHeight - CGRectGetHeight(frame);
        slidingView.frame = newFrame;
    ];

【问题讨论】:

使用自动布局时,不应设置任何框架。你应该通过修改它们的约束来移动你的视图。 【参考方案1】:

您需要在 iOS 8 中设置动画视图的约束,然后自动布局系统处理其余部分。您可以为 NSLayoutConstraint 创建一个 IBOutlet 并简单地更改其常量属性。然后在动画块中对已编辑视图的超级视图调用 layoutIfNeeded 方法。

【讨论】:

以上是关于iOS 8 AutoLayout 改变视图的位置的主要内容,如果未能解决你的问题,请参考以下文章

iOS 使用 Autolayout 以编程方式修复 UIScrollView 中子视图的位置

iOS将autoLayout按钮位置设置为故事板中心的剩余空间

iOS Core Animation具体解释AutoLayout中的动画

ios8 beta 4下无法识别AutoLayout容器相对位置

UICollectionViewCell 子视图的位置错误(自动布局)

IOS / Autolayout:如何修复大文本视图的宽度?