John
John

Reputation: 695

View's width and height do not change after orientation

I use xibs and do most of job programatically.Not touching storyboard. I want to use storyboard just for navigation.

My problem is , after orientation view height and width remain same. How do I get width and height on both portrait and orientation mode after the app run.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, HeaderStyle1Delegate, FieldStyle1Delegate, ButtonStyle1Delegate {

var tableStyle = UITableView()
var header: HeaderStyle1!

override func viewDidLoad() {
    super.viewDidLoad()
    createView() // call function for create header, table and regis xib/UINib
}

func createView() {

    //Create Header
    header = HeaderStyle1(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 80))
    header.delegate = self
    self.view.addSubview(header)

    //Create TableView
    tableStyle.frame = CGRect(x: 0, y: 80, width: self.view.frame.size.width, height: self.view.frame.size.height - 80)
    tableStyle.delegate = self
    tableStyle.dataSource = self
    tableStyle.backgroundColor = UIColor(red: 245.0/255.0, green:
        248.0/255.0, blue: 252.0/255.0, alpha: 1.0)
    tableStyle.separatorColor = UIColor.clear
    tableStyle.allowsSelection = false
    tableStyle.isScrollEnabled = true
......
...
..
}

Screenshoots

enter image description here

enter image description here

My ViewController. (it is full empty as I mentioned)

enter image description here

Upvotes: 1

Views: 757

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

It's better to use constraints in these cases instead of resetting the frames

header.translatesAutoresizingMaskIntoConstraints = false

if #available(iOS 11, *) {

    let guide = view.safeAreaLayoutGuide

    header.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true

    header.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true

    header.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true

} else {


    header.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true

    header.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true

    header.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true


}

header.heightAnchor.constraint(equalToConstant: 80.0).isActive = true

Upvotes: 1

Related Questions