Consider you are having the table view with a separate cell class that will be registered for table view later.
Now, we know how to disable the table view scroll using the table view instance, like in the below line.
tableView.isScrollEnabled = true/false
But what if I require to show some coach marks on the cell class, And I need to lock the table view scroll until that coach marks disappear using cell rather than table view. Because for a cell class table view instance is inaccessible since cell is within table view, not the table view within cell.
I've achieved this by using Notifications and Observers. But Please let me know if this can be achieved in any other way.
CodePudding user response:
Is your target supporting iOS 13 ? If so you can use Combine SDK. It will give you the same principle of notification and observers.
You will need a viewModel conforms to ObservableObject, then you will use @Published property wrapper, lets us easily construct types that emit signals whenever some of their properties were changed.
ViewModel.swift
enum ViewState {
case loading
case loaded
case showCoachMark
case hideCoachMark
}
class ViewModel: ObservableObject {
@Published var state: ViewState = .loading
.....
}
ViewController.swift
import Combine
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let viewModel = ViewModel()
private var cancellable: AnyCancellable?
override func viewDidLoad(){
cancellable = viewModel.$state.sink { value in
// call tableview.isScrollEnabled = true/false
// Please push this back to the main thread if the state has
// been fetched via a request call
}
}
}
CodePudding user response:
Here is simple trick that can answer your question:
class YourTableViewCell: UITableViewCell {
weak var tableView: UITableView? // declare a weak reference to your tableView that contains this cell
func disableScroll() {
tableView?.isScrollEnabled = false
}
func enableScroll() {
tableView?.isScrollEnabled = true
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: YourTableViewCell = ...
cell.tableView = tableView // assign this tableView to weak ref of tableView in YourTableViewCell
}