【问题标题】:Instead of sizeToFit what should I use而不是 sizeToFit 我应该使用什么
【发布时间】:2012-11-19 17:48:04
【问题描述】:

我正在开发一个主视图填满整个屏幕的应用程序。此主视图包含您可以将其视为精灵的子视图。他们使用自己的代码四处游荡。他们四处游荡的逻辑可能会让他们在屏幕外游荡。我想做的是调整主视图的大小,使其包含所有子视图。不过,实际上变化的并不是视图大小。正在改变的是缩放比例。有点像缩小谷歌地图视图。我怎么做?它将是触发此操作的手势识别器。

【问题讨论】:

    标签: ios view sizetofit


    【解决方案1】:

    您应该使用三级视图层次结构:

    • 顶层视图
      • 缩放视图
        • 精灵视图 0
        • 精灵视图 1
        • 精灵视图 2

    设置缩放视图的边界以包含所有精灵视图的框架。然后设置缩放视图的变换,使其适合顶级视图。

    - (void)updateBoundsAndTransformOfView:(UIView *)scaledView {
        CGRect scaledBounds = CGRectNull;
        for (UIView *spriteView in scaledView.subviews) {
            scaledBounds = CGRectUnion(scaledBounds, spriteView.frame);
        }
    
        scaledView.bounds = scaledBounds;
        // Now scaledView's size is large enough to contain all of its subviews,
        // and scaledView's coordinate system origin is at the left edge of the
        // leftmost sprite and the top edge of the topmost sprite.
    
        UIView *topLevelView = scaledView.superview;
        CGRect topLevelBounds = topLevelView.bounds;
        CGFloat xScale =topLevelBounds.size.width / scaledBounds.size.width;
        CGFloat yScale = topLevelBounds.size.height / scaledBounds.size.height;
        CGFloat scale = MIN(xScale, yScale);
        scaledView.transform = CGAffineTransformMakeScale(scale, scale);
        scaledView.center = CGPointMake(CGRectGetMidX(topLevelBounds), CGRectGetMidY(topLevelBounds));
    }
    

    【讨论】:

    • 谢谢。看起来它会起作用,而且我更喜欢它而不是我想到的替代方案,即使用 UIScrollView。我没有想到要添加另一层。谢谢。
    猜你喜欢
    • 2016-05-23
    • 2018-05-10
    • 2014-03-12
    • 2012-12-13
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多