Daniel Daniel - 5 days ago 5
iOS Question

Swift - Use button to manually scroll UITextView

I want to use a button to scroll down or up in

UITextView
,
but I ran into a problem.

Using
textView.setContentOffset(CGPoint(x: 0, y: MyTextView.contentOffset.y + 100), animated: true)
can make my textview scroll down, but it still scrolls when I click the button in the end of text...

like this..

e
f
g




===================


But I want is this..

a
b
c
d
e
f
g
===================


My code is

@IBAction func down(_ sender: UIButton) {
MyTextView.setContentOffset(CGPoint(x: 0, y: MyTextView.contentOffset.y - 100), animated: true)
}

@IBAction func up(_ sender: UIButton) {
MyTextView.setContentOffset(CGPoint(x: 0, y: MyTextView.contentOffset.y - 100), animated: true)
}


please help me!!!

Answer

Try this one

@IBAction func down(_ sender: UIButton) {
    if (textView.contentSize.height>(textView.frame.size.height+textView.contentOffset.y+100)){

        textView.setContentOffset(CGPoint(x:0,y:textView.contentOffset.y + 100), animated: true);
    }
    else{
        textView.setContentOffset(CGPoint(x:0,y:(textView.contentSize.height - textView.frame.size.height)), animated: true)
    }
}
Comments