如何准备重用约束?

如何解决如何准备重用约束?

我有一个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 = truecell.taskNameLabel.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = false时,代码的渲染方式类似于左侧模拟器:https://www.loom.com/share/fcc332ff862741a8ae346e43820b0b60?from_recorder=1

发生的事情是,例如,当第2行没有数量时, new 第2行上的数量也被隐藏(而该单元格应该有数量)。当关于约束的行被注释掉时,所有操作都按预期进行,但是当包含约束时,发生了奇怪的情况。

我如何确保约束(如果单元格中没有数量,则将名称标签居中放置在Y轴上)

很抱歉,如果我不清楚,我真的不确定如何走得更远,坦率地说,迷路了。

对于StackOverflow社区:非常感谢!

解决方法

听起来您想要输出看起来像这样:

enter image description here

如果是这样,这是我如何设计单元格:

enter image description here

那是

  • 一个按钮
  • 带有两个标签的垂直堆栈视图
  • 图片视图

个人资料图片视图的尾随锚距内容视图的尾随锚约束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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-