首页 文章

在屏幕下方加载时,TableViewCell按钮单击未注册

提问于
浏览
0

我的主视图是滚动视图,在此视图中我有一个内容视图 . 在这个视图中,我有三个不同的tableviews . tableviews具有可变数量的行,我在运行时设置每个tableView高度,具体取决于有多少个单元格 .

例如TableView 1的行高为72,运行时有三行 . 因此tableView高度等于72 * 3 = 216

然后我禁止滚动TableViews,以便我可以轻松滚动浏览整个视图 . 在每个tableView单元格中,都有执行某些操作的按钮 . 这些按钮使用按钮标签和与每个按钮绑定的动作完美地工作 . 这是问题,但......

这些按钮仅在加载初始时位于屏幕上时才有效 . 如果我的滚动视图超出屏幕底部,则所有按钮都将变为非活动状态 . TableView越过屏幕边缘并不重要,下面的所有按钮将不再有效 .

在加载tableView数据之前,我已经阅读了一些关于将内容视图高度设置为滚动视图的整个高度的论坛,但这似乎不起作用 . 这是我在加载tableData之前用来更改scrollView / contentView高度的代码 . 我可以显示您认为必要的任何其他代码来帮助解决问题 .

totalHeight = self.friendsTableHeight.constant + self.invitationsTableHeight.constant + self.suggestionsTableHeight.constant + 350
self.scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: totalHeight)
self.contentViewHeight.constant = totalHeight

DispatchQueue.main.async {
    self.suggestionsTable.dataSource = self
    self.friendsTableView.dataSource = self
    self.invitationsTableView.dataSource = self
    self.suggestionsTable.reloadData()
    self.friendsTableView.reloadData()
    self.invitationsTableView.reloadData()
}

我还尝试将我的contentView设置为clipToBounds,但这会切断屏幕下方表格的任何部分 . 现在正在研究这几个小时,并希望有人可能会遇到过这个!

1 回答

  • 0

    如果没有看到更多的代码或者如何设置约束,很难说出你做错了什么 . 然而...

    下面是一个在scrollView中垂直布局的3个tableView的简单示例,它们之间的垂直间距为40磅 . 无论滚动位置如何,单元格中的按钮都能正常工作 .

    故事板布局如下所示:

    enter image description here

    结果:

    enter image description here

    向下滚动后:

    enter image description here

    代码:

    //
    //  TablesInScrollViewController.swift
    //
    //  Created by Don Mag on 11/7/18.
    //
    
    import UIKit
    
    class ButtonCell: UITableViewCell {
    
        let theButton: UIButton = {
            let v = UIButton()
            v.translatesAutoresizingMaskIntoConstraints = false
            v.setContentHuggingPriority(.required, for: .horizontal)
            v.backgroundColor = .yellow
            v.setTitleColor(.blue, for: .normal)
            v.setTitle("Button", for: .normal)
            return v
        }()
    
        let theLabel: UILabel = {
            let v = UILabel()
            v.translatesAutoresizingMaskIntoConstraints = false
            v.backgroundColor = .cyan
            return v
        }()
    
        override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            commonInit()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            commonInit()
        }
    
        func commonInit() -> Void {
    
            contentView.addSubview(theLabel)
            contentView.addSubview(theButton)
    
            NSLayoutConstraint.activate([
    
                theLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8.0),
                theLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8.0),
                theLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8.0),
    
                theButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8.0),
                theButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8.0),
                theButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8.0),
    
                theLabel.trailingAnchor.constraint(equalTo: theButton.leadingAnchor, constant: -8.0),
    
                ])
    
            theButton.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
        }
    
        @objc func buttonTapped(_ sender: Any) {
            print("Button tapped for:", theLabel.text ?? "")
        }
    
    }
    
    class TablesInScrollViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
        @IBOutlet var tableA: UITableView!
        @IBOutlet var tableB: UITableView!
        @IBOutlet var tableC: UITableView!
    
        @IBOutlet var tableAHeightConstraint: NSLayoutConstraint!
        @IBOutlet var tableBHeightConstraint: NSLayoutConstraint!
        @IBOutlet var tableCHeightConstraint: NSLayoutConstraint!
    
        var aData = ["A - 1", "A - 2", "A - 3", "A - 4", "A - 5", "A - 6"]
        var bData = ["B - 1", "B - 2", "B - 3", "B - 4", "B - 5", "B - 6", "B - 7", "B - 8", "B - 9", "B - 10"]
        var cData = ["C - 1", "C - 2", "C - 3", "C - 4"]
    
        var rHeight = 72
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            let theData = tableView.isEqual(tableA) ? aData : tableView.isEqual(tableB) ? bData : cData
            return theData.count
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
            let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonCell", for: indexPath) as! ButtonCell
    
            let theData = tableView.isEqual(tableA) ? aData : tableView.isEqual(tableB) ? bData : cData
            cell.theLabel.text = theData[indexPath.row]
    
            return cell
    
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            [tableA, tableB, tableC].forEach {
                $0?.dataSource = self
                $0?.delegate = self
                $0?.register(ButtonCell.self, forCellReuseIdentifier: "ButtonCell")
                $0?.rowHeight = CGFloat(rHeight)
            }
    
            tableAHeightConstraint.constant = CGFloat(rHeight * aData.count)
            tableBHeightConstraint.constant = CGFloat(rHeight * bData.count)
            tableCHeightConstraint.constant = CGFloat(rHeight * cData.count)
    
        }
    
    }
    

    和故事板源(以帮助您获得正确的约束):

    <?xml version="1.0" encoding="UTF-8"?>
    <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14109" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="llR-vr-4Zy">
        <device id="retina4_7" orientation="portrait">
            <adaptation id="fullscreen"/>
        </device>
        <dependencies>
            <deployment identifier="iOS"/>
            <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
            <capability name="Safe area layout guides" minToolsVersion="9.0"/>
            <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
        </dependencies>
        <scenes>
            <!--Tables In Scroll View Controller-->
            <scene sceneID="7Zm-EI-Mg7">
                <objects>
                    <viewController id="llR-vr-4Zy" customClass="TablesInScrollViewController" customModule="SW4Temp" customModuleProvider="target" sceneMemberID="viewController">
                        <view key="view" contentMode="scaleToFill" id="tw7-gs-oZR">
                            <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="GnA-uY-k8D">
                                    <rect key="frame" x="20" y="40" width="335" height="607"/>
                                    <subviews>
                                        <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="PBs-dW-Koi">
                                            <rect key="frame" x="7.5" y="8" width="319" height="128"/>
                                            <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                            <constraints>
                                                <constraint firstAttribute="height" constant="128" id="BKq-4w-98u"/>
                                            </constraints>
                                        </tableView>
                                        <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="nk6-mF-h3T">
                                            <rect key="frame" x="7.5" y="176" width="319" height="128"/>
                                            <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                            <constraints>
                                                <constraint firstAttribute="height" constant="128" id="Z9y-eh-Yju"/>
                                            </constraints>
                                        </tableView>
                                        <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="Exi-mx-rcW">
                                            <rect key="frame" x="7.5" y="344" width="319" height="128"/>
                                            <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                            <constraints>
                                                <constraint firstAttribute="height" constant="128" id="qti-gs-wLU"/>
                                            </constraints>
                                        </tableView>
                                    </subviews>
                                    <color key="backgroundColor" red="0.0" green="0.58980089430000004" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                    <constraints>
                                        <constraint firstItem="PBs-dW-Koi" firstAttribute="width" secondItem="GnA-uY-k8D" secondAttribute="width" constant="-16" id="Axl-cT-hm3"/>
                                        <constraint firstItem="Exi-mx-rcW" firstAttribute="top" secondItem="nk6-mF-h3T" secondAttribute="bottom" constant="40" id="G1C-SH-ONS"/>
                                        <constraint firstItem="nk6-mF-h3T" firstAttribute="centerX" secondItem="PBs-dW-Koi" secondAttribute="centerX" id="MjW-Yu-9Bi"/>
                                        <constraint firstAttribute="bottom" secondItem="Exi-mx-rcW" secondAttribute="bottom" constant="8" id="R5m-2G-ZHN"/>
                                        <constraint firstItem="PBs-dW-Koi" firstAttribute="top" secondItem="GnA-uY-k8D" secondAttribute="top" constant="8" id="UZj-KF-b8H"/>
                                        <constraint firstItem="PBs-dW-Koi" firstAttribute="leading" secondItem="GnA-uY-k8D" secondAttribute="leading" constant="8" id="bhx-EO-I8M"/>
                                        <constraint firstItem="Exi-mx-rcW" firstAttribute="centerX" secondItem="nk6-mF-h3T" secondAttribute="centerX" id="gF2-Nw-sxy"/>
                                        <constraint firstItem="Exi-mx-rcW" firstAttribute="width" secondItem="nk6-mF-h3T" secondAttribute="width" id="glB-2g-ALO"/>
                                        <constraint firstAttribute="trailing" secondItem="PBs-dW-Koi" secondAttribute="trailing" constant="8" id="n5L-uV-uAN"/>
                                        <constraint firstItem="nk6-mF-h3T" firstAttribute="top" secondItem="PBs-dW-Koi" secondAttribute="bottom" constant="40" id="ppi-8s-Y5S"/>
                                        <constraint firstItem="nk6-mF-h3T" firstAttribute="width" secondItem="PBs-dW-Koi" secondAttribute="width" id="qFz-lA-ieI"/>
                                    </constraints>
                                </scrollView>
                            </subviews>
                            <color key="backgroundColor" red="1" green="0.83234566450000003" blue="0.47320586440000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                            <constraints>
                                <constraint firstItem="V6X-c3-PaY" firstAttribute="trailing" secondItem="GnA-uY-k8D" secondAttribute="trailing" constant="20" id="0Ev-px-vRN"/>
                                <constraint firstItem="GnA-uY-k8D" firstAttribute="top" secondItem="V6X-c3-PaY" secondAttribute="top" constant="20" id="3sa-DD-wMb"/>
                                <constraint firstItem="V6X-c3-PaY" firstAttribute="bottom" secondItem="GnA-uY-k8D" secondAttribute="bottom" constant="20" id="Dji-Cc-aaB"/>
                                <constraint firstItem="GnA-uY-k8D" firstAttribute="leading" secondItem="V6X-c3-PaY" secondAttribute="leading" constant="20" id="ZKZ-mu-117"/>
                            </constraints>
                            <viewLayoutGuide key="safeArea" id="V6X-c3-PaY"/>
                        </view>
                        <connections>
                            <outlet property="tableA" destination="PBs-dW-Koi" id="Cnm-we-nuM"/>
                            <outlet property="tableAHeightConstraint" destination="BKq-4w-98u" id="6mm-8g-BQL"/>
                            <outlet property="tableB" destination="nk6-mF-h3T" id="yEs-cv-Zld"/>
                            <outlet property="tableBHeightConstraint" destination="Z9y-eh-Yju" id="oC8-9g-71b"/>
                            <outlet property="tableC" destination="Exi-mx-rcW" id="UhD-rh-9Kw"/>
                            <outlet property="tableCHeightConstraint" destination="qti-gs-wLU" id="ej2-mK-5YT"/>
                        </connections>
                    </viewController>
                    <placeholder placeholderIdentifier="IBFirstResponder" id="kfo-TI-SEb" userLabel="First Responder" sceneMemberID="firstResponder"/>
                </objects>
                <point key="canvasLocation" x="31" y="48"/>
            </scene>
        </scenes>
    </document>
    

相关问题