我的问题-当我以编程方式将安排的子视图添加到stackview时,它们只是堆积在右上角,如下所示。他们为什么不堆积呢?我已经尝试了很多方法,包括使用具有固有大小的视图。
堆栈视图称为mainStack,来自xib。 mainStack是一个垂直堆栈,其中“对齐”设置为“填充”,“分布”设置为“相等填充”(请参阅此问题底部的设置)。它包含一个带有蓝色背景的UIView。为了这个问题,我使用addArrangedSubviews向mainStack添加了两个视图。这是我得到的:
这是xib的代码:
class TaskSheet: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var mainStack: UIStackView!
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: "TaskSheet", bundle: nil)
nib.instantiate(withOwner: self, options: nil)
contentView.frame = bounds
addSubview(contentView)
}
}
这就是我试图向mainStack添加视图的方式:
class PDFSheet: UIView {
var taskSheet: TaskSheet!
var sheetArray = [UIView]()
func makeSheet() -> [UIView] {
taskSheet = TaskSheet(frame: CGRect(x: 0, y: 0, width: 612, height: 792))
let newView1 = UIView(frame: CGRect(x: 0, y: 0, width: 240, height: 128))
newView1.heightAnchor.constraint(equalToConstant: 128).isActive = true
newView1.widthAnchor.constraint(equalToConstant: 240).isActive = true
newView1.backgroundColor = .green
let newView2 = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 64))
newView2.heightAnchor.constraint(equalToConstant: 64).isActive = true
newView2.widthAnchor.constraint(equalToConstant: 120).isActive = true
newView2.backgroundColor = .yellow
taskSheet.mainStack.addArrangedSubview(newView1)
taskSheet.mainStack.addArrangedSubview(newView2)
sheetArray.append(taskSheet)
return sheetArray
}
}
并且,这是显示stackview设置的xib,以防万一...
我想我知道你要干什么。
这里是一个例子...
xib布局(顶部标签,垂直堆栈视图,底部标签):
堆栈视图的属性:
TaskSheet
,PDFSheet
和示例视图控制器的代码:
class TaskSheet: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet var mainStack: UIStackView!
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: "TaskSheet", bundle: nil)
nib.instantiate(withOwner: self, options: nil)
addSubview(contentView)
NSLayoutConstraint.activate([
// constrain contentView on all 4 sides with 8-pts "padding"
contentView.topAnchor.constraint(equalTo: topAnchor, constant: 8.0),
contentView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8.0),
contentView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8.0),
contentView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8.0),
])
}
}
class PDFSheet: UIView {
var taskSheet: TaskSheet!
var sheetArray = [UIView]()
override init(frame: CGRect) {
super.init(frame: frame)
_ = makeSheet()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
_ = makeSheet()
}
func makeSheet() -> [UIView] {
taskSheet = TaskSheet()
let newView1 = UIView(frame: CGRect(x: 0, y: 0, width: 240, height: 128))
newView1.heightAnchor.constraint(equalToConstant: 128).isActive = true
newView1.widthAnchor.constraint(equalToConstant: 240).isActive = true
newView1.backgroundColor = .green
let newView2 = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 64))
newView2.heightAnchor.constraint(equalToConstant: 64).isActive = true
newView2.widthAnchor.constraint(equalToConstant: 120).isActive = true
newView2.backgroundColor = .yellow
taskSheet.mainStack.addArrangedSubview(newView1)
taskSheet.mainStack.addArrangedSubview(newView2)
sheetArray.append(taskSheet)
addSubview(taskSheet)
taskSheet.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// constrain taskSheet on all 4 sides
taskSheet.topAnchor.constraint(equalTo: topAnchor, constant: 8.0),
taskSheet.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8.0),
taskSheet.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8.0),
taskSheet.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8.0),
])
return sheetArray
}
}
class TaskViewController: UIViewController {
var theSheetView: PDFSheet!
override func viewDidLoad() {
super.viewDidLoad()
theSheetView = PDFSheet()
theSheetView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(theSheetView)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// constrain the sheet view on all top, leading, trailing with 32-pts "padding"
theSheetView.topAnchor.constraint(equalTo: g.topAnchor, constant: 32.0),
theSheetView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 32.0),
theSheetView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -32.0),
// NO height or bottom constraint
])
}
}
这是xib文件的来源(以便于检查):
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="N6d-Cd-Atk">
<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>
<scenes>
<!--Log In View Controller-->
<scene sceneID="e5u-QJ-Bww">
<objects>
<viewController id="b3W-0i-Mlb" customClass="LogInViewController" customModule="scratchy" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="ncx-cU-8Af">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="OSX-B9-w8Z">
<rect key="frame" x="154.5" y="318.5" width="66" height="30"/>
<state key="normal" title="Do Log In"/>
<connections>
<action selector="doLoginTapped:" destination="b3W-0i-Mlb" eventType="touchUpInside" id="j1a-uJ-1IG"/>
</connections>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="This is LogIn VC" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="NsK-V0-VeG">
<rect key="frame" x="126" y="121" width="123" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="NsK-V0-VeG" firstAttribute="centerX" secondItem="ncx-cU-8Af" secondAttribute="centerX" id="QpB-r9-5qU"/>
<constraint firstItem="NsK-V0-VeG" firstAttribute="top" secondItem="EbT-Jq-J3U" secondAttribute="top" constant="77" id="ZKY-xE-pEb"/>
<constraint firstItem="OSX-B9-w8Z" firstAttribute="centerX" secondItem="ncx-cU-8Af" secondAttribute="centerX" id="fMq-4v-XyT"/>
<constraint firstItem="OSX-B9-w8Z" firstAttribute="centerY" secondItem="ncx-cU-8Af" secondAttribute="centerY" id="qVY-nC-PqE"/>
</constraints>
<viewLayoutGuide key="safeArea" id="EbT-Jq-J3U"/>
</view>
<navigationItem key="navigationItem" id="o8k-0O-cNJ"/>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="uP4-Vf-4SL" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="380" y="824"/>
</scene>
<!--Start View Controller-->
<scene sceneID="SdS-pG-Q2l">
<objects>
<viewController storyboardIdentifier="StartVC" id="cLV-i6-MSZ" customClass="StartViewController" customModule="scratchy" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Dy4-oJ-DW4">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="IP4-Qz-zns">
<rect key="frame" x="107" y="318.5" width="161" height="30"/>
<state key="normal" title="Push to go to Log In VC"/>
<connections>
<segue destination="b3W-0i-Mlb" kind="show" id="MFe-2F-dT0"/>
</connections>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="This is Start VC" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="IFb-C0-mX9">
<rect key="frame" x="128.5" y="133" width="118" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="IP4-Qz-zns" firstAttribute="centerX" secondItem="Dy4-oJ-DW4" secondAttribute="centerX" id="0df-jh-VtW"/>
<constraint firstItem="IFb-C0-mX9" firstAttribute="top" secondItem="FgR-v5-onA" secondAttribute="top" constant="89" id="0wq-KY-OwB"/>
<constraint firstItem="IFb-C0-mX9" firstAttribute="centerX" secondItem="Dy4-oJ-DW4" secondAttribute="centerX" id="AbM-cV-Fih"/>
<constraint firstItem="IP4-Qz-zns" firstAttribute="centerY" secondItem="Dy4-oJ-DW4" secondAttribute="centerY" id="OZz-KS-otd"/>
</constraints>
<viewLayoutGuide key="safeArea" id="FgR-v5-onA"/>
</view>
<navigationItem key="navigationItem" id="FZs-4c-uJy"/>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="ZsD-zq-DWe" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-423" y="825"/>
</scene>
<!--Navigation Controller-->
<scene sceneID="eYF-Ds-vCn">
<objects>
<navigationController automaticallyAdjustsScrollViewInsets="NO" id="EqK-Mj-3Vf" sceneMemberID="viewController">
<toolbarItems/>
<navigationBar key="navigationBar" contentMode="scaleToFill" insetsLayoutMarginsFromSafeArea="NO" id="fyf-nl-MqT">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<nil name="viewControllers"/>
<connections>
<segue destination="cLV-i6-MSZ" kind="relationship" relationship="rootViewController" id="4nw-Xk-KCB"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="QOw-4S-yYe" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-1188" y="825"/>
</scene>
<!--Logged In Second View Controller-->
<scene sceneID="vaS-nn-D30">
<objects>
<viewController id="cgP-NN-DdJ" customClass="LoggedInSecondViewController" customModule="scratchy" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="phV-Lb-f4V">
<rect key="frame" x="0.0" y="0.0" width="375" height="647"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="This is Second Logged-In VC" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="plS-RQ-TJc">
<rect key="frame" x="76.5" y="313" width="222.5" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="plS-RQ-TJc" firstAttribute="centerY" secondItem="phV-Lb-f4V" secondAttribute="centerY" id="1l4-Gm-4xX"/>
<constraint firstItem="plS-RQ-TJc" firstAttribute="centerX" secondItem="phV-Lb-f4V" secondAttribute="centerX" id="lgM-6G-ddH"/>
</constraints>
<viewLayoutGuide key="safeArea" id="I3a-uq-iVv"/>
</view>
<navigationItem key="navigationItem" id="ZiS-qO-6ai"/>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="2aj-tp-f02" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="380" y="1493"/>
</scene>
<!--Home View Controller-->
<scene sceneID="aDs-4i-uOT">
<objects>
<viewController storyboardIdentifier="HomeVC" id="2Sw-P5-7xX" customClass="HomeViewController" customModule="scratchy" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="GGR-T3-B1f">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="This is Home VC" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="9r1-tN-d64">
<rect key="frame" x="124.5" y="323" width="126" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="IgB-1W-AgB">
<rect key="frame" x="133.5" y="126" width="108" height="30"/>
<state key="normal" title="Push to Second"/>
<connections>
<segue destination="cgP-NN-DdJ" kind="show" id="xQa-nT-FSl"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="VXN-mx-1xi">
<rect key="frame" x="148.5" y="206" width="78" height="30"/>
<state key="normal" title="Do Log Out"/>
<connections>
<action selector="doLogoutTapped:" destination="2Sw-P5-7xX" eventType="touchUpInside" id="QER-XU-zLa"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="IgB-1W-AgB" firstAttribute="centerX" secondItem="GGR-T3-B1f" secondAttribute="centerX" id="Nel-cp-Vpn"/>
<constraint firstItem="9r1-tN-d64" firstAttribute="centerY" secondItem="GGR-T3-B1f" secondAttribute="centerY" id="XHH-fK-URc"/>
<constraint firstItem="VXN-mx-1xi" firstAttribute="top" secondItem="IgB-1W-AgB" secondAttribute="bottom" constant="50" id="eun-AA-w1O"/>
<constraint firstItem="9r1-tN-d64" firstAttribute="centerX" secondItem="GGR-T3-B1f" secondAttribute="centerX" id="n35-L7-XkI"/>
<constraint firstItem="VXN-mx-1xi" firstAttribute="centerX" secondItem="GGR-T3-B1f" secondAttribute="centerX" id="p2K-Ol-BjT"/>
<constraint firstItem="IgB-1W-AgB" firstAttribute="top" secondItem="r8E-HZ-gYH" secondAttribute="top" constant="126" id="z1y-oX-tvc"/>
</constraints>
<viewLayoutGuide key="safeArea" id="r8E-HZ-gYH"/>
</view>
<navigationItem key="navigationItem" id="EUX-Nq-hb0"/>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="nmk-R4-zEt" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-423" y="1493"/>
</scene>
<!--Task View Controller-->
<scene sceneID="Bmh-xj-2XN">
<objects>
<viewController id="N6d-Cd-Atk" customClass="TaskViewController" customModule="scratchy" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="FcG-3U-rRS">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<viewLayoutGuide key="safeArea" id="pzg-Xt-1YL"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="aSK-QY-KyR" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-425" y="2166"/>
</scene>
</scenes>
</document>
结果: