Reputation: 20804
I have an UITableView
and I need that another class be notified if UITableView
is scrolled but I need that my UIViewController
respond for the "normals" UITableViewDelegate
methods such as func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
by example, its this even possible?
Upvotes: 3
Views: 711
Reputation: 2035
It is possible by implementing a a wrapper class that routes selector calls to one or other delegate.
Here is a working gist that solves the problem: https://gist.github.com/ULazdins/71a2bfd474c7f6fe9d0e61a749271247
Upvotes: 1
Reputation: 100541
You can have a delagate to inform the other class of the scroll event
func scrollViewDidScroll(_ scrollView: UIScrollView) {
delegate?.tableScrolled(_ scrollView: UIScrollView)
}
Upvotes: 1
Reputation: 11928
We solved this through delegates in the following way:
protocol OtherClasscrollDelegate: class {
func scrollViewDidScroll(_ scrollView: UIScrollView)
func scrollViewWillBeginDragging(_ scrollView: UIScrollView)
}
class OtherClass: OtherClasscrollDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
....
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
....
}
}
class ViewController {
weak var otherClassScrollDelegate: OtherClasscrollDelegate?
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.otherClassScrollDelegate?.scrollViewDidScroll(scrollView)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.otherClassScrollDelegate?.scrollViewWillBeginDragging(scrollView)
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
....
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
....
}
}
Upvotes: 3
Reputation: 318934
Since there is only one delegate
property and since UITableViewDelegate
extends UIScrollViewDelegate
, you can only set one object as the delegate.
What you can do is have your view controller implement the table view delegate methods as needed and also have your view controller implement the scroll view delegate methods. But simply have those call the corresponding methods in the other class you have.
Here's a rough example:
class MyViewController: UITableViewDelegate {
// lots of other stuff
let myScrollViewDelegate = YourScrollViewDelegate()
func scrollViewDidScroll(_ scrollView: UIScrollView) {
myScrollViewDelegate.scrollViewDidScroll(scrollView)
}
}
Upvotes: 3
Reputation: 1915
It's not possible to split the scrollViewDelegate
and tableViewDelegate
Into 2 different classes. What you could do is to have it in 1 class, and setup a notificationCenter oberserver
in which you send the needed data as a NSNotification
to the class that needs it.
Upvotes: 1