ScrollView中的Swift CollectionView和TableView

如何解决ScrollView中的Swift CollectionView和TableView

所以,如何在下面的图片中看到,我在ScrollView中具有collectionView和TableView。而且它不按我的预期工作。您可以在gif图片中看到问题。 CollectionView的静态高度= 100,tableview的高度为selfsizeble.StackView的高度和宽度等于ScrollView的高度和宽度。看起来好像有个小错误,但我找不到它。

此处为TableView的AutoSizeClass:

class AutoSizingTableView: UITableView {
    
      override var intrinsicContentSize: CGSize {
          self.layoutIfNeeded()
          return CGSize(width: UIView.noIntrinsicMetric,height: contentSize.height)
      }
      
      override var contentSize: CGSize {
          didSet{
              self.invalidateIntrinsicContentSize()
          }
      }
      
      override func reloadData() {
          super.reloadData()
          self.invalidateIntrinsicContentSize()
      }
    
  }

问题在于带有收藏夹视图的视图位于同一位置,并且不会向上滚动。

enter image description here

How it works

解决方法

根据您的评论“在表视图中禁用了滚动,根本无法滚动” ...您的设置有误。

这里是如何在情节提要中对其进行布局以使其正常工作。请注意,表格视图 必须 已滚动已禁用

enter image description here

以下是该故事板的来源:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16096" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="for-Xa-JUC">
    <device id="retina4_7" orientation="portrait" appearance="light"/>
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="collection view cell content view" minToolsVersion="11.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--Azdaev View Controller-->
        <scene sceneID="UV2-bp-BSw">
            <objects>
                <viewController id="for-Xa-JUC" customClass="AzdaevViewController" customModule="TableAdd" customModuleProvider="target" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="Aiw-Z0-OHR">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="NiW-5R-cfc">
                                <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                                <subviews>
                                    <stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="8" translatesAutoresizingMaskIntoConstraints="NO" id="Iqj-ag-gPR">
                                        <rect key="frame" x="0.0" y="0.0" width="375" height="348"/>
                                        <subviews>
                                            <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Ewg-bZ-eyT">
                                                <rect key="frame" x="0.0" y="0.0" width="375" height="100"/>
                                                <subviews>
                                                    <collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="PVP-gp-7EW">
                                                        <rect key="frame" x="0.0" y="0.0" width="375" height="100"/>
                                                        <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
                                                        <constraints>
                                                            <constraint firstAttribute="height" constant="100" id="4ie-da-XpJ"/>
                                                        </constraints>
                                                        <collectionViewFlowLayout key="collectionViewLayout" scrollDirection="horizontal" automaticEstimatedItemSize="YES" minimumLineSpacing="10" minimumInteritemSpacing="10" id="JhR-eW-5b9">
                                                            <size key="itemSize" width="80" height="80"/>
                                                            <size key="headerReferenceSize" width="0.0" height="0.0"/>
                                                            <size key="footerReferenceSize" width="0.0" height="0.0"/>
                                                            <inset key="sectionInset" minX="0.0" minY="0.0" maxX="0.0" maxY="0.0"/>
                                                        </collectionViewFlowLayout>
                                                        <cells>
                                                            <collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="SimpleCollCell" id="znX-Ra-Axt" customClass="SimpleCollCell" customModule="TableAdd" customModuleProvider="target">
                                                                <rect key="frame" x="0.0" y="10" width="80" height="80"/>
                                                                <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                                                <collectionViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" insetsLayoutMarginsFromSafeArea="NO" id="GWE-KA-31W">
                                                                    <rect key="frame" x="0.0" y="0.0" width="80" height="80"/>
                                                                    <autoresizingMask key="autoresizingMask"/>
                                                                    <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="7U6-uF-qZB">
                                                                            <rect key="frame" x="19" y="30" width="42" height="20.5"/>
                                                                            <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                                            <nil key="textColor"/>
                                                                            <nil key="highlightedColor"/>
                                                                        </label>
                                                                    </subviews>
                                                                    <color key="backgroundColor" red="0.99953407049999998" green="0.98835557699999999" blue="0.47265523669999998" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                                    <constraints>
                                                                        <constraint firstItem="7U6-uF-qZB" firstAttribute="centerY" secondItem="GWE-KA-31W" secondAttribute="centerY" id="8E5-5k-QqV"/>
                                                                        <constraint firstItem="7U6-uF-qZB" firstAttribute="centerX" secondItem="GWE-KA-31W" secondAttribute="centerX" id="FTH-Df-wyE"/>
                                                                    </constraints>
                                                                </collectionViewCellContentView>
                                                                <connections>
                                                                    <outlet property="theLabel" destination="7U6-uF-qZB" id="kcQ-Wy-2wY"/>
                                                                </connections>
                                                            </collectionViewCell>
                                                        </cells>
                                                    </collectionView>
                                                </subviews>
                                                <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
                                                <constraints>
                                                    <constraint firstAttribute="trailing" secondItem="PVP-gp-7EW" secondAttribute="trailing" id="941-fg-5DC"/>
                                                    <constraint firstItem="PVP-gp-7EW" firstAttribute="top" secondItem="Ewg-bZ-eyT" secondAttribute="top" id="9kx-ps-iUv"/>
                                                    <constraint firstItem="PVP-gp-7EW" firstAttribute="leading" secondItem="Ewg-bZ-eyT" secondAttribute="leading" id="OYx-qn-7cl"/>
                                                    <constraint firstAttribute="bottom" secondItem="PVP-gp-7EW" secondAttribute="bottom" id="OgJ-Yv-Jal"/>
                                                </constraints>
                                            </view>
                                            <tableView clipsSubviews="YES" contentMode="scaleToFill" placeholderIntrinsicWidth="infinite" placeholderIntrinsicHeight="240" alwaysBounceVertical="YES" scrollEnabled="NO" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="XGR-gS-YDa" customClass="ContentSizedTableView" customModule="TableAdd" customModuleProvider="target">
                                                <rect key="frame" x="0.0" y="108" width="375" height="240"/>
                                                <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
                                                <prototypes>
                                                    <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="SimpleTableCell" id="LTQ-ke-1N0" customClass="SimpleTableCell" customModule="TableAdd" customModuleProvider="target">
                                                        <rect key="frame" x="0.0" y="28" width="375" height="43"/>
                                                        <autoresizingMask key="autoresizingMask"/>
                                                        <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="LTQ-ke-1N0" id="ILn-2o-e6E">
                                                            <rect key="frame" x="0.0" y="0.0" width="375" height="43"/>
                                                            <autoresizingMask key="autoresizingMask"/>
                                                            <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="QxE-9g-2Hm">
                                                                    <rect key="frame" x="15" y="11" width="345" height="21"/>
                                                                    <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                                    <nil key="textColor"/>
                                                                    <nil key="highlightedColor"/>
                                                                </label>
                                                            </subviews>
                                                            <constraints>
                                                                <constraint firstAttribute="bottomMargin" secondItem="QxE-9g-2Hm" secondAttribute="bottom" id="2kY-7j-i6k"/>
                                                                <constraint firstAttribute="trailingMargin" secondItem="QxE-9g-2Hm" secondAttribute="trailing" id="8Rb-MN-fCq"/>
                                                                <constraint firstItem="QxE-9g-2Hm" firstAttribute="top" secondItem="ILn-2o-e6E" secondAttribute="topMargin" id="IFx-mV-xVp"/>
                                                                <constraint firstItem="QxE-9g-2Hm" firstAttribute="leading" secondItem="ILn-2o-e6E" secondAttribute="leadingMargin" id="SkZ-FP-3Xk"/>
                                                            </constraints>
                                                        </tableViewCellContentView>
                                                        <connections>
                                                            <outlet property="theLabel" destination="QxE-9g-2Hm" id="tCs-qB-RnZ"/>
                                                        </connections>
                                                    </tableViewCell>
                                                </prototypes>
                                            </tableView>
                                        </subviews>
                                    </stackView>
                                </subviews>
                                <constraints>
                                    <constraint firstItem="Iqj-ag-gPR" firstAttribute="width" secondItem="cNU-lA-jis" secondAttribute="width" id="YWn-il-cIA"/>
                                    <constraint firstItem="Iqj-ag-gPR" firstAttribute="bottom" secondItem="78Z-qi-tb8" secondAttribute="bottom" id="dWW-mF-X02"/>
                                    <constraint firstItem="Iqj-ag-gPR" firstAttribute="leading" secondItem="78Z-qi-tb8" secondAttribute="leading" id="jlB-bm-lOp"/>
                                    <constraint firstItem="Iqj-ag-gPR" firstAttribute="top" secondItem="78Z-qi-tb8" secondAttribute="top" id="oPw-KA-7Eb"/>
                                    <constraint firstItem="Iqj-ag-gPR" firstAttribute="trailing" secondItem="78Z-qi-tb8" secondAttribute="trailing" id="t90-TH-ogv"/>
                                </constraints>
                                <viewLayoutGuide key="contentLayoutGuide" id="78Z-qi-tb8"/>
                                <viewLayoutGuide key="frameLayoutGuide" id="cNU-lA-jis"/>
                            </scrollView>
                        </subviews>
                        <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
                        <constraints>
                            <constraint firstItem="NiW-5R-cfc" firstAttribute="top" secondItem="kCj-qX-p52" secondAttribute="top" id="18n-ZT-7rU"/>
                            <constraint firstItem="NiW-5R-cfc" firstAttribute="leading" secondItem="kCj-qX-p52" secondAttribute="leading" id="1BY-QR-X5K"/>
                            <constraint firstItem="NiW-5R-cfc" firstAttribute="trailing" secondItem="kCj-qX-p52" secondAttribute="trailing" id="YHh-qb-ygU"/>
                            <constraint firstItem="NiW-5R-cfc" firstAttribute="bottom" secondItem="kCj-qX-p52" secondAttribute="bottom" id="tzd-Zo-fNv"/>
                        </constraints>
                        <viewLayoutGuide key="safeArea" id="kCj-qX-p52"/>
                    </view>
                    <connections>
                        <outlet property="theCollectionView" destination="PVP-gp-7EW" id="MxW-WG-GPj"/>
                        <outlet property="theTableView" destination="XGR-gS-YDa" id="NhY-EO-L3y"/>
                    </connections>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="nbL-KS-cva" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="447.82608695652175" y="3079.6875"/>
        </scene>
    </scenes>
</document>

和演示代码:

final class ContentSizedTableView: UITableView {
    override var contentSize:CGSize {
        didSet {
            invalidateIntrinsicContentSize()
        }
    }
    override var intrinsicContentSize: CGSize {
        layoutIfNeeded()
        return CGSize(width: UIView.noIntrinsicMetric,height: contentSize.height)
    }
}
class SimpleCollCell: UICollectionViewCell {
    @IBOutlet var theLabel: UILabel!
}
class SimpleTableCell: UITableViewCell {
    @IBOutlet var theLabel: UILabel!
}
class AzdaevViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate {
    
    @IBOutlet var theCollectionView: UICollectionView!
    @IBOutlet var theTableView: ContentSizedTableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        theTableView.dataSource = self
        theTableView.delegate = self
        theCollectionView.dataSource = self
        theCollectionView.delegate = self
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return 30
    }
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let c = tableView.dequeueReusableCell(withIdentifier: "SimpleTableCell",for: indexPath) as! SimpleTableCell
        c.theLabel.text = "Row \(indexPath.row)"
        return c
    }
    func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        return 10
    }
    func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let c = collectionView.dequeueReusableCell(withReuseIdentifier: "SimpleCollCell",for: indexPath) as! SimpleCollCell
        c.theLabel.text = "\(indexPath.item)"
        return c
    }

}

结果:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 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-