如何在swift中更改设备大小时获取子视图的当前大小? [英] how to get current size of a subview when device size changes in swift?

查看:436
本文介绍了如何在swift中更改设备大小时获取子视图的当前大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须查看:view_1和view_2。 view_1高度与主视图控制器高度成正比,我以编程方式将view_2添加为view_1的子视图,其高度成比例。

I have to view: view_1 and view_2 . view_1 height is proportional to the main view controller height and I am adding view_2 programmatically as a subview of view_1 with a proportional height.

问题

当设备尺寸发生变化时说从iPhone 6到iPhone 5 ,view_1正确调整但其高度我传递给绘制其子视图的函数view_2仍然是在界面生成器中设置的,因此它在iPhone 4中从iPhone 6移出界限

when the device size changes say from iPhone 6 to iPhone 5, the view_1 adjust correctly but its height I am passing to a function to draw its subview view_2 is still what was set in interface builder and so it is out of bounds in iPhone 4 moving from iPhone 6

因此,我想知道如何获得正确大小的视图,以便自动调整大小以适应当前设备?

Thus I want to know how can I get the correct size of a view that what resize automatically to fit the current device?

推荐答案

在运行自动布局之前,不会建立视图的大小。您第一次获得正确尺寸的机会在 viewDidLayoutSubviews

The size of the view isn't established until Auto Layout runs. Your first opportunity to get the correct size is in viewDidLayoutSubviews:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // access view size here
}






这是一个完整的示例,它将第二个视图添加为第一个视图的子视图。故事板中添加了红色视图;它是水平和垂直居中的,它的高度/宽度是其超视图的50%。


Here's a complete example that adds a second view as a subview of the first view. The red view was added in the Storyboard; it is centered horizontally and vertically and it's height/width is 50% of its superview.

黄色视图以编程方式添加。它的帧是从红色视图的帧计算为红色视图宽度的50%。

The yellow view is added programmatically. It's frame is computed from the frame of the red view to be 50% of the width of the red view.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var view1: UIView!
    var view2: UIView?

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        if view2 == nil {
            view2 = UIView()
            view2?.backgroundColor = .yellowColor()
            view1.addSubview(view2!)
        }

        let width = view1.frame.size.width
        let height = view1.frame.size.height

        let frame = CGRect(x: width * 0.25, y: height * 0.25, width: width * 0.5, height: height * 0.5)

        view2?.frame = frame
    }
}

不是 viewDidLayoutSubviews 被多次调用,因此每次调用时都必须注意不要添加 view2 。这就是代码检查是否已添加 view2 的原因。

Not that viewDidLayoutSubviews gets called multiple times, so you must take care not to add view2 every time it is called. That is why the code checks to see if view2 has been added.

这篇关于如何在swift中更改设备大小时获取子视图的当前大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆