如何解决如何准备重用约束?
我有一个UITableViewController
,其中包含多个部分。每个部分均包含具有自定义UITableViewCells
的行。该单元格包含4个主要元素:
- 名称标签
- 数量标签
- 检查按钮
- 个人资料图片
我正在努力的是如何重复使用这些单元。在this回答中,我读到与内容无关的事情应该在prepareForReuse
中完成,而与内容相关的“重置”应该在cellForRowAt
中完成。但是,我无法弄清楚该如何做。此刻,似乎有一件主要的事情出错了。
约束未正确“转移”
这是我cellForRowAt
中的代码:
let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell",for: indexPath) as! TaskCell
let currentItem = sections[indexPath.section].items[indexPath.row]
cell.taskNameLabel.text = currentItem.name
cell.uid = currentItem.uid
cell.delegate = self
cell.indexSection = indexPath.section
cell.indexRow = indexPath.row
cell.itemID = currentItem.itemID
cell.items = sections[indexPath.section].items
cell.quantity = ""
cell.quantity = currentItem.quantity
if currentItem.quantity != nil && currentItem.quantity != "" && currentItem.quantity != " " {
cell.quantityLabel.isHidden = false
cell.quantityLabel.text = currentItem.quantity?.uppercased()
cell.taskNameLabel.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = false
} else {
cell.quantityLabel.isHidden = true
cell.taskNameLabel.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
}
if currentItem.uid == Auth.auth().currentUser?.uid {
cell.profilePicture.isHidden = true
} else {
cell.profilePicture.isHidden = false
}
if currentItem.checked {
cell.checkBoxOutlet.setBackgroundImage(#imageLiteral(resourceName: "checkBoxFILLED "),for: UIControl.State.normal)
} else {
cell.checkBoxOutlet.setBackgroundImage(#imageLiteral(resourceName: "checkBoxOUTLINE "),for: UIControl.State.normal)
}
注释掉行cell.taskNameLabel.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
和cell.taskNameLabel.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = false
时,代码的渲染方式类似于左侧模拟器:https://www.loom.com/share/fcc332ff862741a8ae346e43820b0b60?from_recorder=1
发生的事情是,例如,当第2行没有数量时, new 第2行上的数量也被隐藏(而该单元格是应该有数量)。当关于约束的行被注释掉时,所有操作都按预期进行,但是当包含约束时,发生了奇怪的情况。
我如何确保约束(如果单元格中没有数量,则将名称标签居中放置在Y轴上)
?很抱歉,如果我不清楚,我真的不确定如何走得更远,坦率地说,迷路了。
对于StackOverflow社区:非常感谢!
解决方法
听起来您想要输出看起来像这样:
如果是这样,这是我如何设计单元格:
那是
- 一个按钮
- 带有两个标签的垂直堆栈视图
- 图片视图
个人资料图片视图的尾随锚距内容视图的尾随锚约束16点,并且具有CenterY锚。
按钮被限制在前导:0,CenterY ... 和 顶部和底部都大于或等于6
堆栈视图受约束Leading-to-ButtonTrailing:8,Trailing-to-ProfileImageViewLeading:-8,CenterY ... 和 顶部和底部都大于或等于4
这样,我们告诉自动布局以使像元高度:
-
比堆栈视图高至少
- 8个点 比按钮高
- 至少 12点
当我们有数量时,两个标签都将被填充,并且不隐藏。因此,堆栈视图将比按钮高,并且其顶部/底部约束将优先。
如果我们没有有数量,则“名称”标签将显示,但“数量”标签将被隐藏。因此,该按钮将更高,并且其“顶部/底部”约束将优先。
在两种情况下,所有内容都将在单元格中保持垂直居中。
这是单元格类的简化版本:
class TaskCell: UITableViewCell {
@IBOutlet var checkBoxOutlet: UIButton!
@IBOutlet var taskNameLabel: UILabel!
@IBOutlet var quantityLabel: UILabel!
@IBOutlet var profilePicture: UIImageView!
func fillData(_ task: Task,profileImage: UIImage?) -> Void {
let sysName: String = task.checked ? "largecircle.fill.circle" : "circle"
if let img = UIImage(systemName: sysName) {
checkBoxOutlet.setBackgroundImage(img,for: .normal)
}
taskNameLabel.text = task.name.uppercased()
// make sure quantity is not " "
let q = task.quantity.trimmingCharacters(in: .whitespacesAndNewlines)
quantityLabel.text = q.uppercased()
quantityLabel.isHidden = q == ""
profilePicture.image = profileImage
profilePicture.isHidden = profileImage == nil
}
}
这是情节提要的源代码,因此您可以检查单元格的布局:
<?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="0rh-3w-bzr">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17125"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Example Table View Controller-->
<scene sceneID="RP6-4O-gi2">
<objects>
<tableViewController id="0rh-3w-bzr" customClass="ExampleTableViewController" customModule="DelMe" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="9oA-oN-4sp">
<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"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="taskCell" rowHeight="104" id="0OE-gK-JaO" customClass="TaskCell" customModule="DelMe" customModuleProvider="target">
<rect key="frame" x="0.0" y="28" width="375" height="104"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="0OE-gK-JaO" id="GeB-v3-7H5">
<rect key="frame" x="0.0" y="0.0" width="375" height="104"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Rrf-x2-kgv">
<rect key="frame" x="16" y="36.5" width="32" height="31"/>
<constraints>
<constraint firstAttribute="width" constant="32" id="aBr-zc-Hi1"/>
<constraint firstAttribute="width" secondItem="Rrf-x2-kgv" secondAttribute="height" multiplier="1:1" id="t6J-WJ-4Dq"/>
</constraints>
<state key="normal" backgroundImage="circle" catalog="system"/>
</button>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="4" translatesAutoresizingMaskIntoConstraints="NO" id="ugR-45-YpU">
<rect key="frame" x="56" y="31" width="255" height="42.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="d1t-1z-Pyt">
<rect key="frame" x="0.0" y="0.0" width="255" height="20.5"/>
<color key="backgroundColor" red="0.55634254220000001" green="0.97934550050000002" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="efT-dG-UOP">
<rect key="frame" x="0.0" y="24.5" width="255" height="18"/>
<color key="backgroundColor" red="0.99953407049999998" green="0.98835557699999999" blue="0.47265523669999998" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="15"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
</stackView>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="Hlp-8o-qHO">
<rect key="frame" x="319" y="40" width="24" height="24"/>
<color key="tintColor" red="1" green="0.14913141730000001" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstAttribute="width" constant="24" id="4ax-ud-MaN"/>
<constraint firstAttribute="width" secondItem="Hlp-8o-qHO" secondAttribute="height" multiplier="1:1" id="V9i-E8-rqH"/>
</constraints>
</imageView>
</subviews>
<constraints>
<constraint firstAttribute="bottomMargin" relation="greaterThanOrEqual" secondItem="ugR-45-YpU" secondAttribute="bottom" constant="4" id="5Tm-8S-wzZ"/>
<constraint firstItem="Rrf-x2-kgv" firstAttribute="top" relation="greaterThanOrEqual" secondItem="GeB-v3-7H5" secondAttribute="topMargin" constant="6" id="D7D-hZ-deP"/>
<constraint firstItem="ugR-45-YpU" firstAttribute="leading" secondItem="Rrf-x2-kgv" secondAttribute="trailing" constant="8" id="F7l-d8-Raf"/>
<constraint firstItem="ugR-45-YpU" firstAttribute="centerY" secondItem="GeB-v3-7H5" secondAttribute="centerY" id="Gzg-V9-jnW"/>
<constraint firstItem="Rrf-x2-kgv" firstAttribute="centerY" secondItem="GeB-v3-7H5" secondAttribute="centerY" id="Kmx-OQ-LVg"/>
<constraint firstItem="ugR-45-YpU" firstAttribute="top" relation="greaterThanOrEqual" secondItem="GeB-v3-7H5" secondAttribute="topMargin" constant="4" id="LVP-0M-KbC"/>
<constraint firstAttribute="trailingMargin" secondItem="Hlp-8o-qHO" secondAttribute="trailing" constant="16" id="QpT-89-Kci"/>
<constraint firstAttribute="bottomMargin" relation="greaterThanOrEqual" secondItem="Rrf-x2-kgv" secondAttribute="bottom" constant="6" id="STP-yS-UR0"/>
<constraint firstItem="Rrf-x2-kgv" firstAttribute="leading" secondItem="GeB-v3-7H5" secondAttribute="leadingMargin" id="Sum-If-WiN"/>
<constraint firstItem="Hlp-8o-qHO" firstAttribute="centerY" secondItem="GeB-v3-7H5" secondAttribute="centerY" id="h42-Iy-CAV"/>
<constraint firstItem="Hlp-8o-qHO" firstAttribute="leading" secondItem="ugR-45-YpU" secondAttribute="trailing" constant="8" id="wTj-7Z-ZCr"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="checkBoxOutlet" destination="Rrf-x2-kgv" id="EVr-hk-wdw"/>
<outlet property="profilePicture" destination="Hlp-8o-qHO" id="HjC-EX-P2D"/>
<outlet property="quantityLabel" destination="efT-dG-UOP" id="vzF-FI-zX3"/>
<outlet property="taskNameLabel" destination="d1t-1z-Pyt" id="kSQ-K6-gqc"/>
</connections>
</tableViewCell>
</prototypes>
<connections>
<outlet property="dataSource" destination="0rh-3w-bzr" id="Iqt-W7-ziA"/>
<outlet property="delegate" destination="0rh-3w-bzr" id="CJ8-AF-j5x"/>
</connections>
</tableView>
</tableViewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="jyI-jf-7cF" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="183.19999999999999" y="180.35982008995504"/>
</scene>
</scenes>
<resources>
<image name="circle" catalog="system" width="128" height="121"/>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。