如何在新行时自动向下滚动textview

时间:2017-11-14 17:49:56

标签: swift cocoa

在swift 4.0中用于可可应用程序

如果有一个新行,你如何让textview自动滚动下来 加入文字?

是否有内置函数?

我似乎找不到办法做到这一点。

chatplace.scroll(<#T##point: NSPoint##NSPoint#>)

1 个答案:

答案 0 :(得分:-1)

这是一个有效的简单示例:

import UIKit

class ViewController: UIViewController {

    var count = 0
    var timer:Timer?
    @IBOutlet weak var textView: UITextView!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.isScrollEnabled = true
        textView.becomeFirstResponder()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        timer = Timer(timeInterval: 0.125, repeats: true, block: { (timer) in
            self.count += 1
            self.textView.text.append("\n\(self.count) This is another line")
        })
        if let timer = timer {
            RunLoop.current.add(timer, forMode: .commonModes)
        }
    }
}

结果:

output

如果您想以编程方式滚动,请执行此操作:

func scrollToEnd(_ someTextView:UITextView) {
    let bottom = NSMakeRange(someTextView.text.lengthOfBytes(using: .utf8)-1, 1)
    someTextView.scrollRangeToVisible(bottom)
}