wefcwesdc
wefcwesdc

Reputation: 23

the height and the width of ChildViewController's view is different to the ones of its parentsViewController's view

I've added a ChildViewController to ViewController and self.view(the parentsViewController's view) has ChildViewController's view as its subview. I gave constraints to the childViewController's view. all the constants are 0, which means its height and width should be the same as the ones of ViewController.

as below:

  ChildViewController.view.translatesAutoresizingMaskIntoConstraints = false
  ChildViewController.view.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
  ChildViewController.view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0).isActive = true
  ChildViewController.view.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 0).isActive = true
  ChildViewController.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0).isActive = true

and when I rotate the simulator, their sizes are different.

when it's portrait

self.view height: 736.0
self.view is width: 414.0
ChildVC height: 414.0
ChildVC width: 736.0

when it's landscape

self.view height: 414.0
self.view is width: 736.0
ChildVC height: 736.0
ChildVC width: 414.0

I'm not sure where I'm doing wrong. any help would be appreciated. thank you.

Upvotes: 0

Views: 584

Answers (2)

DonMag
DonMag

Reputation: 77423

First note: when posting a question, it helps if you include your actual code and as much information as needed. The code in your question doesn't show how you're loading the child controller, nor how you are checking the view sizes.

Here is a complete example:

class ParentViewController: UIViewController {
    
    // save a reference to the added child controller so we can use it later
    //  we *could* get it later with:
    //      self.children.first
    //  but this helps keep things clear
    var childVCRef: ChildViewController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // make sure we properly load the child controller and its view
        guard let childVC = storyboard?.instantiateViewController(withIdentifier: "childVC") as? ChildViewController,
              let childView = childVC.view
        else {
            fatalError("Could not instantiate ChildViewController and view!!!")
        }
        
        self.addChild(childVC)
        
        childView.translatesAutoresizingMaskIntoConstraints = true
        view.addSubview(childView)
        NSLayoutConstraint.activate([
            childView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0),
            childView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0),
            childView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0),
            childView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0),
        ])
        
        // finish up the add child process
        childVC.didMove(toParent: self)
        
        // our saved reference
        self.childVCRef = childVC
        
        // tap anywhere to print the frames and bounds to debug console
        let t = UITapGestureRecognizer(target: self, action: #selector(self.didTap(_:)))
        view.addGestureRecognizer(t)
    }
    
    @objc func didTap(_ g: UITapGestureRecognizer) -> Void {
        if let childView = childVCRef?.view {
            print("child view frame:", childView.frame)
            print("self view frame: ", view.frame)
            print("child view bounds:", childView.bounds)
            print("self view bounds: ", view.bounds)
        }
    }
    
}

class ChildViewController: UIViewController {
}

The debug output (on iPhone 8 Plus):

Before rotation...

child view frame: (0.0, 0.0, 414.0, 736.0)
self view frame:  (0.0, 0.0, 414.0, 736.0)
child view bounds: (0.0, 0.0, 414.0, 736.0)
self view bounds:  (0.0, 0.0, 414.0, 736.0)

After rotation...

child view frame: (0.0, 0.0, 736.0, 414.0)
self view frame:  (0.0, 0.0, 736.0, 414.0)
child view bounds: (0.0, 0.0, 736.0, 414.0)
self view bounds:  (0.0, 0.0, 736.0, 414.0)

My Storyboard looks like this:

enter image description here

and here's the Storyboard source to test it:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17156" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="kLU-os-Aay">
    <device id="retina3_5" orientation="portrait" appearance="light"/>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17125"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="System colors in document resources" minToolsVersion="11.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--Parent View Controller-->
        <scene sceneID="BUx-ms-dfu">
            <objects>
                <viewController id="kLU-os-Aay" customClass="ParentViewController" customModule="TableAdd" customModuleProvider="target" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="aha-n9-zpP">
                        <rect key="frame" x="0.0" y="0.0" width="320" height="480"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" textAlignment="center" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="aNw-CK-Ha7">
                                <rect key="frame" x="30.5" y="192.5" width="259.5" height="95.5"/>
                                <string key="text">Parent
View Controller</string>
                                <fontDescription key="fontDescription" type="system" pointSize="40"/>
                                <nil key="textColor"/>
                                <nil key="highlightedColor"/>
                            </label>
                        </subviews>
                        <viewLayoutGuide key="safeArea" id="EgR-uj-Wqw"/>
                        <color key="backgroundColor" systemColor="systemBackgroundColor"/>
                        <constraints>
                            <constraint firstItem="aNw-CK-Ha7" firstAttribute="centerY" secondItem="aha-n9-zpP" secondAttribute="centerY" id="Gm5-hu-1XP"/>
                            <constraint firstItem="aNw-CK-Ha7" firstAttribute="centerX" secondItem="aha-n9-zpP" secondAttribute="centerX" id="cKo-Qe-PaP"/>
                        </constraints>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dOa-Qb-1Sa" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-49" y="301"/>
        </scene>
        <!--Child View Controller-->
        <scene sceneID="S1F-Fh-BIa">
            <objects>
                <viewController storyboardIdentifier="childVC" id="2Dw-FZ-578" customClass="ChildViewController" customModule="TableAdd" customModuleProvider="target" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="cUH-MF-5Zw">
                        <rect key="frame" x="0.0" y="0.0" width="320" height="480"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" textAlignment="center" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="UCh-4h-xoX">
                                <rect key="frame" x="30.5" y="192.5" width="259.5" height="95.5"/>
                                <string key="text">Child
View Controller</string>
                                <fontDescription key="fontDescription" type="system" pointSize="40"/>
                                <nil key="textColor"/>
                                <nil key="highlightedColor"/>
                            </label>
                        </subviews>
                        <viewLayoutGuide key="safeArea" id="adq-eR-YNk"/>
                        <color key="backgroundColor" red="0.46202266219999999" green="0.83828371759999998" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="UCh-4h-xoX" firstAttribute="centerY" secondItem="cUH-MF-5Zw" secondAttribute="centerY" id="A7L-CD-TYj"/>
                            <constraint firstItem="UCh-4h-xoX" firstAttribute="centerX" secondItem="cUH-MF-5Zw" secondAttribute="centerX" id="thX-2b-mJH"/>
                        </constraints>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="bTn-X0-Pmx" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="591" y="300"/>
        </scene>
    </scenes>
    <resources>
        <systemColor name="systemBackgroundColor">
            <color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
        </systemColor>
    </resources>
</document>

Upvotes: 0

Claudio
Claudio

Reputation: 5183

Try implementing the viewWillTransitionToSize:withTransitionCoordinator: method on the view controller, and then call setNeedsUpdateConstraints() on the views:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    view.setNeedsUpdateConstraints()
    ChildViewController.view.setNeedsUpdateConstraints()
}

Upvotes: 1

Related Questions