从NIB加载UIView - 错误的帧大小

时间:2013-09-20 05:05:37

标签: ios

好的,所以我在界面构建器中创建了UIView。我正在使用AutoLayout,我有一个视图的子视图固定到所有四个方面。

这是我不明白的地方。当我使用loadNibNamed加载此NIB文件时。然后我得到了对视图的引用。我为这个视图设置了框架。然而,当我访问子视图时(使用[containerView viewWithTag:1]),它的帧没有自动调整大小。是什么赋予了?如果更改父视图的帧,为什么子视图帧也不会更改?

没有任何意义。

为什么不能只加载UIView,设置它的框架并根据需要调整所有子视图(特别是因为我使用的是AutoLayout!)?

编辑:要清楚,我想要做的就是能够在IB中使用适当的UIView约束定义AutoLayout层次结构,然后能够在屏幕上加载和显示该视图在不同的尺寸?为什么这么难?

3 个答案:

答案 0 :(得分:13)

更改视图的几何体时,UIKit不会立即更新子视图几何体。它批量更新效率。

在运行事件处理程序之后,UIKit会检查是否需要在屏幕窗口层次结构中布置任何视图。如果找到任何内容,则通过解决布局约束(如果有的话)将其排除,然后发送layoutSubviews

如果您想立即解决约束并布置视图的子视图,只需将layoutIfNeeded发送到视图:

someView.frame = CGRectMake(0, 0, 200, 300);
[someView layoutIfNeeded];
// The frames of someView.subviews are now up-to-date.

答案 1 :(得分:1)

我也有同样的问题,我正在创建一个教程视图,其中我想在滚动视图中添加多个UIViews。当我试图从xib获取帧时,它总是给出320,因为页面的偏移是错误的,我的观点在iPhone6和6plus中看起来很糟糕。

然后我使用纯自动布局方法,即不使用框架,而是通过VFL添加约束,以便子视图完全适合超视图。下面是我从Xib创建大约20个UIViews并正确添加到scrollview

的代码快照

这里的完整代码ScrollViewAutolayout

 Method to layout the childviews in the scrollview.
 @param nil
 @result layout the child views
 */
-(void)layoutViews
{
    NSMutableString *horizontalString = [NSMutableString string];
    // Keep the start of the horizontal constraint
    [horizontalString appendString:@"H:|"];
    for (int i=0; i<viewsArray.count; i++) {
        // Here I am providing the index of the array as the view name key in the dictionary
        [viewsDict setObject:viewsArray[i] forKey:[NSString stringWithFormat:@"v%d",i]];
        // Since we are having only one view vertically, then we need to add the constraint now itself. Since we need to have fullscreen, we are giving height equal to the superview.
        NSString *verticalString = [NSString stringWithFormat:@"V:|[%@(==parent)]|", [NSString stringWithFormat:@"v%d",i]];
        // add the constraint
        [contentScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:verticalString options:0 metrics:nil views:viewsDict]];
        // Since we need to horizontally arrange, we construct a string, with all the views in array looped and here also we have fullwidth of superview.
        [horizontalString appendString:[NSString stringWithFormat:@"[%@(==parent)]", [NSString stringWithFormat:@"v%d",i]]];
    }
    // Close the string with the parent
    [horizontalString appendString:@"|"];
    // apply the constraint
    [contentScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:horizontalString options:0 metrics:nil views:viewsDict]];
}

答案 2 :(得分:0)

不幸的是Rob接受的答案对我没有用。这是有用的:

var Twit = require('twit')
var T = new Twit({
    consumer_key:         '...',
    consumer_secret:      '...',
    access_token:         '...',
    access_token_secret:  '...'
})
var stream = T.stream('user');
stream.on('direct_message', function (eventMsg) {
    console.log(eventMsg)
})
相关问题