swiftanimationscrollviewcontentoffset

Swift contentOffset scroll


I am developing a small application for tvOS where I need to show a UITextView.

Unfortunately sometimes this text can't fit inside the screen, that's why I need a way to scroll to the bottom of it programmatically.

I've tried using the following code:

self.setContentOffset(offset, animated: true)

It's actually working as intended, except for the fact that I need to handle the animation speed, so that the user can actually read; at the moment it's too fast.

This is what I tried to do, but with little success:

let offset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
UIView.animate(withDuration: 4, animations: {
  self.setContentOffset(offset, animated: false)
})

I need a way to keep the text in place and scroll it to show the missing lines.

I am using a UITextView inside an UIScrollView.

Thanks.


Solution

  • If anyone is looking for a solution, this is what I ended up using:

    var textTopDistance = 100
    //calculate height of the text not being displayed
    textNotVisibleHeight = descriptionLabel.contentSize.height - scrollView.bounds.size.height
    
    func scrollText() {
        //start new thread
        DispatchQueue.main.async() {
            //animation
            UIView.animate(withDuration: 6, delay: 2, options: UIViewAnimationOptions.curveLinear, animations: {
                //set scrollView offset to move the text
                self.scrollView.contentOffset.y = CGFloat(self.textNotVisibleHeight - self.textTopDistance)
            }, completion: nil)
        }
    }
    

    It's not perfect I know, but at least it's working as intended.