【问题标题】:the height and the width of ChildViewController's view is different to the ones of its parentsViewController's viewChildViewController 的视图的高度和宽度与其 parentViewController 的视图不同
【发布时间】:2020-09-24 08:16:51
【问题描述】:

我在 ViewController 中添加了一个 ChildViewController,并且 self.view(parentViewController 的视图)将 ChildViewController 的视图作为其子视图。我对 childViewController 的视图进行了限制。所有的常量都是0,也就是说它的高宽应该和ViewController的一样。

如下:

  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

当我旋转模拟器时,它们的大小是不同的。

当它是肖像时

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

当它是风景时

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

我不确定我在哪里做错了。任何帮助,将不胜感激。谢谢。

【问题讨论】:

  • 您何时/如何查看视图大小?我刚刚做了一个快速测试,旋转后的帧(和边界)是一样的。

标签: ios swift


【解决方案1】:

尝试在视图控制器上实现viewWillTransitionToSize:withTransitionCoordinator: 方法,然后在视图上调用setNeedsUpdateConstraints()

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

【讨论】:

  • 还要检查视图控制器包含的要求:developer.apple.com/library/archive/featuredarticles/…
  • 感谢您的帮助。很抱歉,它仍然是一样的.. 你介意我添加更多信息吗?.. 在模拟器上,childViewConroller 的视图与 ViewController 的视图一样是全屏的。看起来它们的尺寸相同,但是当我调用“打印”方法来查看它们每个的框架尺寸时..它们不一样..它们反过来..
  • 我又做了一次。现在它们的尺寸相同,但是当它是横向时,它们的高度是 736,宽度是 414,当它是纵向时,它们的高度是 414,宽度是 736,我认为应该反过来?
【解决方案2】:

第一个注意事项:发布问题时,如果您包含实际代码和所需的尽可能多的信息,这会有所帮助。您问题中的代码没有显示您如何加载子控制器,也没有显示您如何检查视图大小。

这是一个完整的例子:

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

调试输出(在 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)

我的故事板如下所示:

这是用于测试它的 Storyboard 源代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 2018-10-26
    • 2014-08-10
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 2016-04-18
    相关资源
    最近更新 更多