【问题标题】:Xcode 12, "Vary for Traits" does not work (as expected)Xcode 12,“因特征而异”不起作用(如预期的那样)
【发布时间】:2021-09-15 07:53:26
【问题描述】:

我有一个相对简单的布局,它分为两个主要部分,我用两个UIViews 将其包含在内,以便于管理。

我的目标是提供两种不同的布局,一种用于纵向,一种用于横向。

我的第一个想法是对“宽度”和“高度”都使用“Vary for Traits”,因此,我将情节提要设置为纵向模式,单击“Vary for Traits”,我应用了我想要的特征在纵向模式下,单击“完成”,切换到横向模式并重复该过程。

如您所见,在情节提要中切换方向效果很好

除了,当我在设备上运行它时......它不工作......正如预期的那样

好的????,所以我想,我回去再做一次,但这一次只是改变“宽度”,再一次,它不起作用。

所以,我当时想,我会去老学校。我会添加每个约束并为特定尺寸类设置一个变体......

(我对两个方向都有不同的约束,因此单个约束对两个方向都没有变体)

而且......再一次,这不起作用。在有人告诉我需要在两个方向上勾选“已安装”之前,不,它没有,这只会让 Xcode 生气并在控制台中吐出很多讨厌的 cmets。

“问题”

那么,“简单”的问题是,我做错了什么?我是否错过了一些非常明显的东西可以使这项工作,或者对肖像和风景有单独的约束只是一个非常愚蠢的想法(我虽然“Vary for Traits”基本上是这样做的)

一个“hacky”解决方法

因此,在花了很多时间在这之后,我又回到了过去用于手动创建 UI 的旧“工作流程”

从为每个变体手动创建的约束点开始,我基本上将所有横向和纵向约束放入单独的 IBOutlet 集合中,当调用 viewWillTransition 时,手动取消/激活所需的约束组...

class ViewController: UIViewController {

    @IBOutlet var landscapeConstraints: [NSLayoutConstraint]!
    @IBOutlet var portraitConstraints: [NSLayoutConstraint]!

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    enum Orientation {
        case landscape
        case portrait
        case unknown
    }
    
    fileprivate var lastOrientation: Orientation = .unknown
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        updateCurrentConstraints(toSize: view.bounds.size)
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate { (ctx) in
            self.updateCurrentConstraints(toSize: size)
        } completion: { (ctx) in
        }
    }
    
    func updateCurrentConstraints(toSize size: CGSize) {
        var orientation: Orientation = .portrait
        
        if size.width > size.height {
            orientation = .landscape
        }
        
        guard orientation != lastOrientation else { return }
        lastOrientation = orientation

        guard let portraitConstraints = portraitConstraints, let landscapeConstraints = landscapeConstraints else {
            print("No constraits")
            return
        }
        
        var activeConstraints = portraitConstraints
        var inactiveConstraints = landscapeConstraints

        if orientation == .landscape {
            activeConstraints = landscapeConstraints
            inactiveConstraints = portraitConstraints
        }

        for constraint in inactiveConstraints {
            constraint.isActive = false
        }
        for constraint in activeConstraints {
            constraint.isActive = true
        }
        self.view.setNeedsLayout()
        self.view.layoutIfNeeded()
    }
}

这行得通,我希望它没有,我希望我刚刚做了一些非常愚蠢的事情......除了hacky解决方法

如果您没有太多事情可做并且想搞砸它,有一个 source repo 我用来测试这个概念并提出我的“超级、很棒”的解决方法,我很感激任何类型的情节提要相关问题都是......代码的完整痛苦

【问题讨论】:

  • “这行得通,我希望它没有,我希望我刚刚做了一些非常愚蠢的事情......除了hacky解决方法”这不是hacky。这是非常标准的,我建议您这样做并感到高兴。 :)
  • 我玩过你的源代码库(帮助很多!),我注意到了一些事情:如果你在 Storyboard 中使用 iPhone Pro Max,它将具有 RxC 和 CxR 大小类.但是,如果您在更小尺寸的设备上进行测试,它将具有横向 CxC。在模拟器中运行 Pro Max 似乎没有问题。你尝试过这些不同的场景吗?
  • 是的,可能有助于在这里学习信息表stackoverflow.com/questions/52317545/…
  • @JoshGrant 这是一些巧妙的建议。为了记录,我在故事板和设备上都使用 iPhone 11" ...因为,理智:P

标签: ios swift xcode storyboard


【解决方案1】:

您遇到的问题是您只为wC hRwR hC 设置了Trait Variations ...所以当您遇到wC hC 之类的组合时,您的约束不知道该怎么做( iPhone 8 / iPhone SE 2 / 等)或wR hR(iPad)。

您要做的是为 Height 类改变您的特征。

这是它在 Storyboard 中的外观:

如果我选择 RedView 的 width = 175 约束,属性检查器会显示:

与 RedView 的 width = 250 约束相比:

这是此布局的 Storyboard 源代码...它将正确处理设备旋转,需要 NO 代码:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17701" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="5gV-rv-xrH">
    <device id="retina6_1" orientation="landscape" appearance="light"/>
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17703"/>
        <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>
        <!--View Controller-->
        <scene sceneID="HjL-cd-83j">
            <objects>
                <viewController id="5gV-rv-xrH" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="hIj-xH-n33">
                        <rect key="frame" x="0.0" y="0.0" width="896" height="414"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <button opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Q3p-xw-14f" userLabel="LeftButton">
                                <rect key="frame" x="64" y="5.5" width="46" height="30"/>
                                <color key="backgroundColor" red="0.97625964880000005" green="0.85085996409999998" blue="0.83597719680000004" alpha="1" colorSpace="custom" customColorSpace="displayP3"/>
                                <state key="normal" title="Button"/>
                            </button>
                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="This is a title" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="35a-vA-spC" userLabel="TitleLabel">
                                <rect key="frame" x="118" y="0.0" width="660" height="41"/>
                                <color key="backgroundColor" red="0.83216959239999999" green="0.98548370600000001" blue="0.47333085539999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                <fontDescription key="fontDescription" style="UICTFontTextStyleTitle0"/>
                                <nil key="textColor"/>
                                <nil key="highlightedColor"/>
                            </label>
                            <button opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="OqS-4d-vWh" userLabel="RightButton">
                                <rect key="frame" x="786" y="5.5" width="46" height="30"/>
                                <color key="backgroundColor" red="0.97625964880000005" green="0.85085996409999998" blue="0.83597719680000004" alpha="1" colorSpace="custom" customColorSpace="displayP3"/>
                                <state key="normal" title="Button"/>
                            </button>
                            <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="TjE-LU-Mo5" userLabel="RedView">
                                <rect key="frame" x="60" y="49" width="175" height="219"/>
                                <color key="backgroundColor" red="0.96804410220000003" green="0.21863630410000001" blue="0.1990364194" alpha="1" colorSpace="custom" customColorSpace="displayP3"/>
                                <constraints>
                                    <constraint firstAttribute="width" constant="175" id="FPV-f9-dlF"/>
                                    <constraint firstAttribute="width" constant="250" id="NhS-uQ-oMA"/>
                                    <constraint firstAttribute="width" secondItem="TjE-LU-Mo5" secondAttribute="height" multiplier="0.8" id="PY6-e6-WhI"/>
                                </constraints>
                                <variation key="default">
                                    <mask key="constraints">
                                        <exclude reference="NhS-uQ-oMA"/>
                                    </mask>
                                </variation>
                                <variation key="heightClass=regular">
                                    <mask key="constraints">
                                        <exclude reference="FPV-f9-dlF"/>
                                        <include reference="NhS-uQ-oMA"/>
                                    </mask>
                                </variation>
                            </view>
                            <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Y45-dN-gv7" userLabel="YellowView">
                                <rect key="frame" x="243" y="49" width="609" height="344"/>
                                <color key="backgroundColor" red="0.98267000910000002" green="0.80788773300000005" blue="0.061180472370000002" alpha="1" colorSpace="custom" customColorSpace="displayP3"/>
                            </view>
                        </subviews>
                        <viewLayoutGuide key="safeArea" id="9Rq-n0-LVs"/>
                        <color key="backgroundColor" systemColor="systemBackgroundColor"/>
                        <constraints>
                            <constraint firstItem="Y45-dN-gv7" firstAttribute="leading" secondItem="9Rq-n0-LVs" secondAttribute="leading" id="6IU-UQ-CvM"/>
                            <constraint firstItem="TjE-LU-Mo5" firstAttribute="top" secondItem="35a-vA-spC" secondAttribute="bottom" constant="8" id="BpX-Pw-rla"/>
                            <constraint firstItem="35a-vA-spC" firstAttribute="leading" secondItem="Q3p-xw-14f" secondAttribute="trailing" constant="8" id="FyN-qU-7qE"/>
                            <constraint firstItem="35a-vA-spC" firstAttribute="top" secondItem="9Rq-n0-LVs" secondAttribute="top" id="G1f-Jl-psr"/>
                            <constraint firstItem="Y45-dN-gv7" firstAttribute="top" secondItem="35a-vA-spC" secondAttribute="bottom" constant="8" id="KOB-Fp-exO"/>
                            <constraint firstItem="35a-vA-spC" firstAttribute="centerX" secondItem="hIj-xH-n33" secondAttribute="centerX" id="W6m-QY-p2X"/>
                            <constraint firstItem="Y45-dN-gv7" firstAttribute="leading" secondItem="TjE-LU-Mo5" secondAttribute="trailing" constant="8" id="XLC-WY-foP"/>
                            <constraint firstItem="9Rq-n0-LVs" firstAttribute="bottom" secondItem="Y45-dN-gv7" secondAttribute="bottom" id="esx-I8-2Kb"/>
                            <constraint firstItem="TjE-LU-Mo5" firstAttribute="centerX" secondItem="hIj-xH-n33" secondAttribute="centerX" id="j57-y5-TqD"/>
                            <constraint firstItem="9Rq-n0-LVs" firstAttribute="trailing" secondItem="Y45-dN-gv7" secondAttribute="trailing" id="lLd-bZ-wF2"/>
                            <constraint firstItem="Q3p-xw-14f" firstAttribute="centerY" secondItem="35a-vA-spC" secondAttribute="centerY" id="m4s-gF-g1G"/>
                            <constraint firstItem="OqS-4d-vWh" firstAttribute="leading" secondItem="35a-vA-spC" secondAttribute="trailing" constant="8" id="quQ-DP-nmi"/>
                            <constraint firstItem="9Rq-n0-LVs" firstAttribute="trailing" secondItem="OqS-4d-vWh" secondAttribute="trailing" constant="20" id="uDD-sD-XqW"/>
                            <constraint firstItem="Q3p-xw-14f" firstAttribute="leading" secondItem="9Rq-n0-LVs" secondAttribute="leading" constant="20" id="wgq-II-OyY"/>
                            <constraint firstItem="OqS-4d-vWh" firstAttribute="centerY" secondItem="35a-vA-spC" secondAttribute="centerY" id="wyP-rt-5dh"/>
                            <constraint firstItem="Y45-dN-gv7" firstAttribute="top" secondItem="TjE-LU-Mo5" secondAttribute="bottom" constant="8" id="xQD-Ne-8vP"/>
                            <constraint firstItem="TjE-LU-Mo5" firstAttribute="leading" secondItem="9Rq-n0-LVs" secondAttribute="leading" constant="16" id="zcb-xN-hZU"/>
                        </constraints>
                        <variation key="default">
                            <mask key="constraints">
                                <exclude reference="j57-y5-TqD"/>
                                <exclude reference="xQD-Ne-8vP"/>
                                <exclude reference="6IU-UQ-CvM"/>
                            </mask>
                        </variation>
                        <variation key="heightClass=regular">
                            <mask key="constraints">
                                <exclude reference="zcb-xN-hZU"/>
                                <include reference="j57-y5-TqD"/>
                                <exclude reference="KOB-Fp-exO"/>
                                <include reference="xQD-Ne-8vP"/>
                                <exclude reference="XLC-WY-foP"/>
                                <include reference="6IU-UQ-CvM"/>
                            </mask>
                        </variation>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="AZb-ld-i79" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="74.400000000000006" y="908.09595202398805"/>
        </scene>
    </scenes>
    <resources>
        <systemColor name="systemBackgroundColor">
            <color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
        </systemColor>
    </resources>
</document>

【讨论】:

  • 但是,如果我使用 wC/hR 设备,当它旋转时,我会遇到这个问题。我在情节提要中使用 iPhone 11 设置了约束,并在物理 iPhone 11 设备上对其进行了测试。但是,据我所知,您的观点仍然有效,只是不适用于这个特定问题
  • @MadProgrammer - 你是说我给你的布局不起作用吗?它适用于任何模拟器以及我拥有的 3 部手机:7 (wC hR / wC hC)、11 Pro (wC hR / wC hC)。和 Xr (wC hR / wR hC) ... Xr 应该与 11 相同。
  • 实际上我只是说我在故事板和物理设备上都使用了 11 进行测试,在物理设备上它无法工作 - 有什么理由会发生这种情况吗?如果我能解决这个问题,我会更欢迎调整 wC/wC .. 和 iPad 的约束:P
猜你喜欢
  • 1970-01-01
  • 2018-02-22
  • 1970-01-01
  • 2017-02-14
  • 2011-05-22
  • 2013-05-15
  • 1970-01-01
  • 1970-01-01
  • 2014-05-16
相关资源
最近更新 更多