【问题标题】:View Controller not respecting XIB autoresizing mask视图控制器不遵守 XIB 自动调整大小掩码
【发布时间】:2020-05-26 05:34:59
【问题描述】:

CustomUIView: UIView 类型的 XIB 中创建了 UIView 子类。它包含几个出口,每个出口都使用自动调整大小(不是自动布局)。

这个XIB的视图是这样加载的:

// In CustomUIView class

  // Initializer used by Interface Builder.
  required init?(coder: NSCoder) {
    super.init(coder: coder)
    initialize()
  }

  func initialize() {
    // Load the view
    let contentView = // typical func to load view from NIB. Owner argument is self. 
    addSubview(contentView)
   }

这个 CustomUIView 被添加到一个视图控制器中,如下所示:

问题是视图控制器的视图不遵守 XIB 中定义的自动调整参数。

现在,理论上可以将视图控制器的视图告诉clip to bounds,但这不是一个合适的解决方案。我错过了什么?

【问题讨论】:

  • 你需要设置你的contentView从xib加载时的框架。
  • contentView.frame = bounds 不会产生任何变化。
  • 我马上看到 2 个问题。在故事板中实例化的视图不会自动从 xib 中实例化。您是否验证过 xib 甚至正在使用?此外,您将自动布局(在情节提要中)与自动调整大小的蒙版混合在一起,这并不总是正确的。如果你在xib中切换到自动布局,它会起作用吗?
  • 视图在其 xib 中实例化。见initialize()。当情节提要通过情节提要实例化XIB时(因为我们告诉它UIView实际上是CustomUIView: UIView,它将使用init(coder:)初始化xib,然后调用ìnitialize()`。我确实尝试使用auto所有内容的布局但不起作用,这告诉我框架有问题或将约束从一个视图传递到另一个视图。
  • 发现了问题。非常感谢@DonMag。如果您更改您的答案以包含我输入的内容,我会将您的答案标记为正确答案。

标签: ios swift uiview xib


【解决方案1】:

感谢@donmag 间接指出解决方案。

这是作者所没有的 @donmag 所拥有的。

autoresize 掩码需要翻译成约束:

  1. 点击您的 XIB 视图。

  2. 将布局属性更改为“将掩码转换为约束”。

【讨论】:

    【解决方案2】:

    如果没有看到更多细节,这有点难以判断,但是......

    这是一个对我有用的示例(非常接近您显示的布局):

    它在 Storyboard 中的布局方式:

    结果:

    旋转(显示自动调整大小):


    TwoLabelView.swift 类:

    class TwoLabelView: UIView {
    
        @IBOutlet var contentView: UIView!
        @IBOutlet var topLabel: UILabel!
        @IBOutlet var botLabel: UILabel!
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            setup()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setup()
        }
    
        func setup() {
            let nib = UINib(nibName: "TwoLabelView", bundle: nil)
            nib.instantiate(withOwner: self, options: nil)
            addSubview(contentView)
    
            contentView.frame = self.bounds
    
        }
    }
    

    以及,TwoLabelView.xib 文件的来源:

    <?xml version="1.0" encoding="UTF-8"?>
    <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="15505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
        <device id="retina4_7" orientation="portrait" appearance="light"/>
        <dependencies>
            <deployment identifier="iOS"/>
            <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15510"/>
            <capability name="Safe area layout guides" minToolsVersion="9.0"/>
            <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
        </dependencies>
        <objects>
            <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="TwoLabelView" customModule="scratchy" customModuleProvider="target">
                <connections>
                    <outlet property="botLabel" destination="AKB-d8-jMk" id="QpL-mN-x4M"/>
                    <outlet property="contentView" destination="iN0-l3-epB" id="klb-G5-hj6"/>
                    <outlet property="topLabel" destination="btE-jS-Ur5" id="LkK-0w-J4z"/>
                </connections>
            </placeholder>
            <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
            <view contentMode="scaleToFill" id="iN0-l3-epB">
                <rect key="frame" x="0.0" y="0.0" width="233" height="71"/>
                <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                <subviews>
                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="btE-jS-Ur5">
                        <rect key="frame" x="16" y="8" width="197" height="21"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES" flexibleMaxY="YES"/>
                        <color key="backgroundColor" red="0.79527050256729126" green="0.96349185705184937" blue="0.73112398386001587" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <fontDescription key="fontDescription" type="system" pointSize="17"/>
                        <nil key="textColor"/>
                        <nil key="highlightedColor"/>
                    </label>
                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="AKB-d8-jMk">
                        <rect key="frame" x="16" y="37" width="197" height="21"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" flexibleMinY="YES" heightSizable="YES"/>
                        <color key="backgroundColor" red="0.0" green="0.47790580987930298" blue="0.99864691495895386" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <fontDescription key="fontDescription" type="system" pointSize="17"/>
                        <nil key="textColor"/>
                        <nil key="highlightedColor"/>
                    </label>
                </subviews>
                <color key="backgroundColor" red="0.68716365098953247" green="0.31972628831863403" blue="0.86903256177902222" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
                <viewLayoutGuide key="safeArea" id="vUN-kp-3ea"/>
                <point key="canvasLocation" x="282.39999999999998" y="-218.1409295352324"/>
            </view>
        </objects>
    </document>
    

    编辑

    IB中xib的另一种看法:

    注意事项:

    • 文件的所有者设置为我们的自定义类
    • xib 的视图本身连接到@IBOutlet var contentView: UIView!

    编辑 2

    要确保从 xib 加载的视图正确调整大小,可以:

    A) 将 xib 中 contentViewLayout 属性设置为 Translates Mask Into Constraints,或

    B) 如果Layout 设置为Automatic,我们可以修改我们的setup() func:

    func setup() {
        let nib = UINib(nibName: "TwoLabelView", bundle: nil)
        nib.instantiate(withOwner: self, options: nil)
        addSubview(contentView)
    
        // make sure we're using the right sizing method
        if contentView.translatesAutoresizingMaskIntoConstraints == false {
            contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        }
    
        contentView.frame = self.bounds
    
    }
    

    【讨论】:

    • 太棒了。这意味着我必须设置/取消设置一些标志。问:你在哪里定义 contentView 在你的 xib init 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多