View Controller не соблюдает маску авторазмера XIB - PullRequest
1 голос
/ 10 февраля 2020

Подкласс UIView был создан в XIB типа CustomUIView: UIView. Он содержит несколько выходов, каждое из которых использует автоматическое изменение размера (НЕ автоматическое расположение).

enter image description here enter image description here enter image description here

Это представление 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 добавляется в контроллер представления следующим образом: enter image description here

Проблема заключается в том, что представление контроллера представления не учитывает параметры автоматического изменения размера, определенные в XIB. ,

enter image description here

Теперь, теоретически, можно сказать представлению контроллера вида clip to bounds, но это не является правильным решением. Что мне не хватает?

Ответы [ 2 ]

1 голос
/ 11 февраля 2020

Спасибо @donmag за косвенное указание на решение.

Вот что у автора не было у @donmag.

Маски авторазмера должны быть переведены в ограничения:

  1. Щелкните по представлению XIB.
    enter image description here

  2. Измените свойство макета на «переводит маски в ограничения». enter image description here

0 голосов
/ 11 февраля 2020

Сложно сказать, не видя больше деталей, но ...

Вот пример, который работает для меня (довольно близко к макету, который вы показываете):

enter image description here enter image description here enter image description here

Как это расположено в раскадровке:

enter image description here

Результат:

enter image description here

Поворот (для отображения автоматического изменения размера):

enter image description here


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>

Редактировать

Другой вид XIB в IB:

enter image description here

Примечания:

  • Владелец файла настроен на наш пользовательский класс
  • Само представление xib подключено к @IBOutlet var contentView: UIView!

Редактировать 2

Чтобы убедиться, что размер загруженного из xib представления изменяется правильно, либо:

A) Установите свойство Layout для contentView в xib на Translates Mask Into Constraints или

B) Если для Layout установлено значение Automatic, мы можем изменить setup() fun c:

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

}
...