【问题标题】:How to programmatically set a subview's frame to fit it inside its superview?如何以编程方式设置子视图的框架以使其适合其父视图?
【发布时间】:2014-09-12 12:57:41
【问题描述】:

我需要以编程方式执行以下操作。我怎样才能做到这一点?代码应该足够动态以适应横向内的纵向视图。视图不是 UIImageViews。

【问题讨论】:

    标签: ios view frame addsubview


    【解决方案1】:

    如果您不介意在项目中包含AVFoundation 框架,可以使用:AVMakeRectWithAspectRatioInsideRect(CGSize aspectRatio, CGRect boundingRect);

    它的文档指出:

    返回一个按比例缩放的 CGRect,该 CGRect 在边界 CGRect 内保持 CGSize 指定的纵横比。

    它可以用作:

    subview.frame = AVMakeRectWithAspectRatioInsideRect(subview.bounds.size, superview.bounds);
    

    参数:

    aspectRatio:你要保持的宽高比(纵横比)。

    boundingRect:你想适应的边界矩形。

    【讨论】:

    • 包含 AVFoundation 框架的缺点是什么?一些性能问题或..
    • 不,真的不应该有任何缺点@NerminSehic
    【解决方案2】:
    float ratio = subView.bounds.size.height/subView.bounds.size.width;
    
    [subView setFrame:CGRectMake(0,0,superView.bounds.size.width,superView.bounds.size.width*ratio)];
    [subView setCenter:CGPointMake(superView.bounds.size.width/2,superView.bounds.size.height/2)];
    

    【讨论】:

    • 我喜欢您将视图居中的方式。但是您设置框架的方式不是动态的,尽管它适用于示例。
    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多