ios - UITableView 仅向下滚动

标签 ios swift uitableview uikit

我想配置一个UITableView,使其只能向下滚动。换句话说,禁用表格 View 向上滚动。人们会怎样做呢?

最佳答案

详细信息

  • Xcode 14.2
  • swift 5.7.2

解决方案

import UIKit

class ViewController: UIViewController {
    private weak var tableView: UITableView!
    private var previousContentOffset = CGPoint()
    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(tableView)
        tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        tableView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        self.tableView = tableView
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .gray
    }
}

// MARK: UITableViewDelegate

extension ViewController: UITableViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView === tableView {
            if previousContentOffset.y > scrollView.contentOffset.y {
                scrollView.contentOffset.y = previousContentOffset.y
            }
            previousContentOffset = scrollView.contentOffset
        }
    }
}

// MARK: UITableViewDataSource

extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int { 1 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 1000 }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(indexPath)"
        return cell
    }
}

关于ios - UITableView 仅向下滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44980886/

相关文章:

ios - 滚动时读取 UIImage 数据,优缺点

ios - 高度从 0 变为默认大小后单元格不显示

ios - UITextField 阴影不会显示

swift - 委托(delegate) - 从不同的 View Controller 更改变量

ios - 如何在重定向到/login后再次登录而不出现任何http错误

swift - 是否可以手动传输 pod 文件而不是运行 `pod install` ?

ios - Swift:从 AppDelegate 中的 UNTextInputNotificationAction 获取内容

iphone - 在 Xcode 4.2 中以编程方式编写 iPhone 应用程序的 UITableView

html - iOS Safari 手机 : Doesn't show huge images in correct size

ios - 关闭 View Controller 时的 Exc_bad_access