我想配置一个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/