2

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.

Problem

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?

Community
  • 1
  • 1
irkinosor
  • 766
  • 12
  • 26

3 Answers3

7

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.


iPhone 4s Simulator Portrait


iPhone 5s Simulator Landscape


iPhone 5s Rotation exmaple

vacawama
  • 150,663
  • 30
  • 266
  • 294
1

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

let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
Mohith P
  • 585
  • 5
  • 14
  • I don't want the screen size but the size of the subview in the device when its size change and the subview size is adjusted by the system – irkinosor Jun 22 '16 at 10:48
1

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) 
Jugal K Balara
  • 917
  • 5
  • 15