Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect TextView Scrolling to Show a Button in Swift 3.0

I have a TextView and a hidden button within a UIView, and I'm trying to detect when the user scrolls down to the bottom of a long list of text and to show the hidden button when they reach the bottom. I saw some old posts on how it was done in Obj-C using scrollViewDidScroll, but not really sure how to do that with swift, or how to do it with a TextView instead of a ScrollView. Any help would be great as I haven't gone very far with this one.

So far this is my attempt at translating the obj-c post to swift, but it hasn't worked for me, in fact I'm not even sure when the function is called:

 import UIKit

 class MainVC: UIViewController, UIScrollViewDelegate {

    @IBOutlet var textView: UIScrollView!
    @IBOutlet var button: UIButton!

    override func viewDidLoad() {

        super.viewDidLoad()

        textView.delegate = self


    }

   func scrollViewDidScroll(textV: UIScrollView) {

        if (textV.contentOffset.y >= textV.contentSize.height - textV.frame.size.height)
        {
            button.isHidden = false
        }
    }

}

Thanks for any help in advance :)

like image 455
SwiftStarter Avatar asked Oct 20 '16 05:10

SwiftStarter


Video Answer


2 Answers

UITextView is subclass of UIScrollView and if you look to declaration, you will see, that it is UIScrollViewDelegate by default, so you can remove the UIScrollViewDelegate at the declaration of your controller. Instead, make your controller UITextViewDelegate which allows it to call scrollViewDidScrollMethod.

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var textView: UITextView! {
        didSet {
            textView.delegate = self
        }
    }
    @IBOutlet weak var button: UIButton! {
        didSet {
            button.hidden = true
        }
    }

    func scrollViewDidScroll(scrollView: UIScrollView) {
        button.hidden = scrollView.contentOffset.y + scrollView.bounds.height < scrollView.contentSize.height
    }
}
like image 193
Maksym Musiienko Avatar answered Sep 24 '22 17:09

Maksym Musiienko


(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height

if (bottomEdge >= scrollView.contentSize.height) {

    self.yourButtonName.hidden = true
    }
}
like image 23
Nandini Prashant Barve Avatar answered Sep 22 '22 17:09

Nandini Prashant Barve