If you want to Make the scroll of a TableView inside ScrollView behave naturally? Modified Daniel’s answer to make it more efficient and bug free.
Here is a quick example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var tableHeight: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() //Set table height to cover entire view //if navigation bar is not translucent, reduce navigation bar height from view height tableHeight.constant = self.view.frame.height-64 self.tableView.isScrollEnabled = false //no need to write following if checked in storyboard self.scrollView.bounces = false self.tableView.bounces = true } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let label = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 30)) label.text = "Section 1" label.textAlignment = .center label.backgroundColor = .yellow return label } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = "Row: \(indexPath.row+1)" return cell } func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.scrollView { tableView.isScrollEnabled = (self.scrollView.contentOffset.y >= 200) } if scrollView == self.tableView { self.tableView.isScrollEnabled = (tableView.contentOffset.y > 0) } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.