我想使用一个按钮滚动 down 或 up in UITextView
,但是我遇到了一个问题。
使用textView.setContentOffset(CGPoint(x: 0, y: MyTextView.contentOffset.y + 100), animated: true)
可以使我的文本视图向下滚动,但是当我单击文本末尾的按钮时,它仍然会滚动...
喜欢..
e
f
g
===================
,但我想要这个..
a
b
c
d
e
f
g
===================
我的代码是
@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)
}
请帮助我!
尝试这个
@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)
}
}
我已经测试并有效。检查一下
@IBOutlet weak var textView: UITextView!
@IBAction func up(_ sender: UIButton) {
if textView.contentOffset.y < 100{
textView.setContentOffset(CGPoint.zero, animated: true)
}else{
textView.setContentOffset(CGPoint(x: 0, y: textView.contentOffset.y-100), animated: true)
}
}
@IBAction func down(_ sender: UIButton) {
if textView.contentOffset.y > textView.contentSize.width - textView.frame.size.height{
textView.setContentOffset(CGPoint(x: 0, y: textView.contentSize.height-textView.frame.size.height), animated: true)
}else{
textView.setContentOffset(CGPoint(x: 0, y: textView.contentOffset.y+100), animated: true)
}
}
您可能想检查当前偏移量是什么,并且仅移动所需的金额。例如,为了向下滚动,请尝试以下类似。然后,您应该能够对其进行调整并进行相反的滚动。
struct Constants {
static let preferredScrollAmount: CGFloat = 100.0
}
@IBAction func downButtonTapped(_ sender: UIButton) {
// Get the current offset, content height, text view height and work out the scrollable distance for the text view
let currentOffset: CGFloat = textView.contentOffset.y
let contentHeight: CGFloat = textView.contentSize.height
let textViewHeight: CGFloat = textView.frame.size.height
let scrollableDistance = contentHeight - textViewHeight
// Check that the current offset isn't beyond the scrollable area otherwise return (no need to scroll)
guard currentOffset < scrollableDistance else { return }
// Work out how far we can move
let distanceWeCanMove = scrollableDistance - currentOffset
// Get the distance we should move (the smaller value so it doesn't go past the end)
let distanceToScroll = min(distanceWeCanMove, Constants.preferredScrollAmount)
// Do the scrolling
textView.setContentOffset(CGPoint(x: 0, y: currentOffset + distanceToScroll), animated: true)
}