how to get current size of a subview when device size changes in swift?

耗尽温柔 提交于 2019-12-02 02:49:38

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
}

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.

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
    }
}

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.




Try this,you can find the screen size of device.

let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

Try to do this in Viewdidload First you need to set view one frame

view_1.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height) 

then set frame of view_2

view_2.frame = CGRectMake(0 , 0, view_1.frame.width, view_1.frame.height) 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!