向上或向下滚动文本视图的按钮

Buttons to scroll textview up or down

我知道如何创建具有滚动功能的文本视图,但这需要您触摸文本视图内部并手动向上或向下滚动文本。 我想创建一个 UITextview 和两个按钮。这些按钮充当滚动按钮,一个向上滚动,另一个向下滚动,让用户控制滚动速度。 我见过的许多示例都涉及自动滚动到底部,这不是我想要的。 谁能建议一种在按下按钮时向上或向下滚动一到三行的方法? 非常感谢!

    @IBOutlet weak var textView: UITextView!

    @IBAction func upButton(_ sender: Any) {
        let currentOffset = textView.contentOffset
        let padding : CGFloat = 10 // Change as your choice
        textView.setContentOffset(
            CGPoint(
                x: currentOffset.x,
                y: currentOffset.y - padding < 0 ? 0 : currentOffset.y - padding
            ),
            animated: true
        )

    }


    @IBAction func downButton(_ sender: Any) {
        let currentOffset = textView.contentOffset
        let contentHeight = textView.contentSize.height
        let padding : CGFloat = 10.0 // Change as your choice
        textView.setContentOffset(
            CGPoint(
                x: currentOffset.x,
                y: currentOffset.y + padding > contentHeight ? contentHeight : currentOffset.y + padding
            ),
            animated: true
        )
    }

使用这个 - 单击按钮时更新内容偏移量

@IBAction func btnUPClick(_ sender: UIButton)
{
    if txtv.contentSize.height > txtv.contentOffset.y + txtv.frame.size.height // this condition checks textview reached at bottom
    {
    txtv.setContentOffset(CGPoint(x:txtv.contentOffset.x , y:txtv.contentOffset.y + 10////change it according to requirement ) , animated: true)
    }

}

@IBAction func btnDownClick(_ sender: UIButton)
{
    if txtv.contentOffset.y > 0 // // this condition checks textview reached at top
    {
    txtv.setContentOffset(CGPoint(x:txtv.contentOffset.x , y:txtv.contentOffset.y - 10 //change it according to requirement  ) , animated: true)
    }
}

如果您有任何问题,请告诉我...

您可以使用 UIScrollViewDelegate 函数向上或向下滚动 contentView,而且 UIScrollViewUITextView 的超类,阅读 apple documentation.[=16 了解更多信息=]

首先对您的 class 实施 UIScrollViewDelegate 并使用以下简单方法。

var scrollSpeed = CGFloat()

func toScrollUp(){
   scrollSpeed += 100
   myTextView.scrollRectToVisible(CGRect(x: 0, y: scrollSpeed, width: myTextView.frame.width, height: myTextView.frame.height), animated: true)
}

func toScrollDown(){
   scrollSpeed -= 100
   myTextView.scrollRectToVisible(CGRect(x: 0, y: scrollSpeed, width: myTextView.frame.width, height: myTextView.frame.height), animated: true)
}