iOS - 如何在从远程服务流式传输时在 UITextView 中开始新行

iOS - How to start a new line in UITextView while streaming from remote service

在我的 ios 应用程序中,我将文本从远程服务流式传输到 UITextView。

 @IBOutlet weak var streamingResult: UITextView!

 // Store streaming results in a String called results
 var results : String = ""

我不知道什么时候有短信进来。但是每当有暂停时,我想在 UILabel 上开始一个新行。

所以我求助于使用 NSTimer 来检测何时没有文本持续 3 秒,如下所示:

var timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, 
selector: "pauseExists", userInfo: nil, repeats: false)

当没有输入文本时,我的选择器按预期命中,我尝试添加一个换行符,如下所示:

@objc func pauseExists() {
    print("No stream for 3 seconds")

    guard let currentText = self.streamingResult.text else { return }
    if !currentText.isEmpty {
       self.results.append("\n")
       self.streamingResult.text = self.results
    } 
}

这不起作用,下一个结果会在上一个结果之后添加。正确的做法是什么?

这里有一个更好的例子。请改用 UITextView。它更好,并且带有免费的 UIScroll。

let label : UITextView = {
        let label = UITextView()
        label.backgroundColor = .red
        label.isEditable = false
        return label
}()

lazy var appendButton : UIButton = {
    let button = UIButton()
    button.setTitle("Append", for: .normal)
    button.backgroundColor = .red
    return button
}()

var foo : String = ""

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.addSubview(appendButton)
    appendButton.translatesAutoresizingMaskIntoConstraints = false
    appendButton.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
    appendButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
    appendButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
    appendButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
    appendButton.addTarget(self, action: #selector(appendButtonPressed), for: .touchUpInside)


    self.view.addSubview(label)
    label.translatesAutoresizingMaskIntoConstraints = false
    label.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    label.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
    label.widthAnchor.constraint(equalToConstant: 200).isActive = true
    label.heightAnchor.constraint(equalToConstant: 200).isActive = true

    var timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.pauseExists), userInfo: nil, repeats: true)
}

@objc func pauseExists() {
    print("No stream for 1 second")
    foo.append("\n")
    label.text = foo
}

@objc func appendButtonPressed (sender: UIButton!) {
    foo.append("New Line")
    label.text = foo
}

运行 此代码在一个空项目中,您将看到每次按下追加按钮时如何追加新行。希望对你有帮助