bobcat
bobcat

Reputation: 187

setting slider value to currently reading position in textview

I have a slider sitting vertically next to a textview. Currently, if I grab the slider and pull down, it scrolls down the text in the textView. However, reading the text in the textview does not update the position of the thumb on the slider. How can I do this?

Upvotes: 1

Views: 201

Answers (2)

Nancy Madan
Nancy Madan

Reputation: 447

Please make sure, Your slider's UserInteractionEnabled is true. You can check it in Storyboard, in Attribute Inspector. And for updating textView reading, Use this code :- Where you set the text :-

  slider.maximumValue = Float(text.contentSize.height) - Float(text.frame.size.height)

And the make slider's valueChanged IBAction :-

  @IBAction func actionSlider(_ sender: UISlider) {
        txt.contentOffset = CGPoint.init(x: 0, y: Int(sender.value))
    }

Upvotes: 0

shio
shio

Reputation: 408

You have to watch UITextView's contentOffset changes. UITextView is a subclass of UIScrollView, so you can use UIScrollViewDelegate methods. When you scroll textView, scrollViewDidScroll method will be called. Based on current contentOffset, you can update your slider accordingly.

class ViewController: UIViewController {
    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.delegate = self
    }
}

extension ViewController: UITextViewDelegate { }

extension ViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView === textView {
            // update your slider based on scrollView.contentOffset
        }
    }
}

Upvotes: 1

Related Questions