【问题标题】:Show one word in tableviewcell at a time一次在 tableviewcell 中显示一个单词
【发布时间】:2018-03-03 07:28:06
【问题描述】:

我试图在表格视图单元格中显示每个单词,每个单词之间有 2 秒的停顿。这可能吗?我不想继续重新加载修改单元格并像这样重新加载它:

var fullNameArr = message.characters.split{$0 == " "}.map(String.init)
        var firstWord = true
        for word in fullNameArr {
            if firstWord {
                firstWord = false
             captionsArray.append(CaptionObject(isMacro:isMacro, number: numberToCall!.number, caption: word, time: String(describing:currentTimeInMiliseconds())))
                self.reloadTableAndScroll()
            } else {
                 let cap = self.captionsArray.last!
                cap.caption = cap.caption + " " + word
                captionsArray.remove(at: captionsArray.count)
                captionsArray.append(cap)
                self.reloadTableAndScroll()
            }


            self.reloadTableAndScroll()
        }

【问题讨论】:

  • 每 2 秒运行一次计时器,在表格加载完成后显示下一个单元格文本。遗漏了一些更精细的细节,但也许这对你有用

标签: ios swift tableview reload


【解决方案1】:

您可以使用Timer 来实现此目的。

要创建Timer,只需在类的顶部声明计时器变量,并在viewDidLoad 方法中初始化它:

var timer: Timer?

override func viewDidLoad() {
    super.viewDidLoad()

    timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(addWordCell), userInfo: nil, repeats: true)

    // ...
}

现在每 2 秒,您的 addWordCell 方法将被调用一次。 顺便说一句,我建议你使用insertsRows 方法而不是一直重新加载你的表格视图,这样会更有效率。例如,您可以像这样编写 addWordCell 方法:

var words = [String]()

var currentWordIndex = 0

let sentence = "Hello how are you doing today?"

func addWordCell() {

    let wordsArray = sentence.components(separatedBy: " ").map({ $0 })

    guard currentWordIndex < wordsArray.count else {
        return
    }

    words.append(wordsArray[currentWordIndex])

    tableView.beginUpdates()
    tableView.insertRows(at: [IndexPath(row: words.count-1, section: 0)], with: .fade)
    tableView.endUpdates()

    currentWordIndex += 1
}

您当然需要更改表格视图数据源方法:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return words.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)

    cell.textLabel?.text = words[indexPath.row]

    return cell
}

现在,如果您想在新单元格出现时添加一个漂亮的小渐变效果,您可以使用willDisplayCell 方法:

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    cell.alpha = 0.0

    UIView.animate(withDuration: 0.6, animations: {

        cell.alpha = 1.0
    })
}

就是这样!显然,您可以进一步改进代码,并对其进行自定义以满足您的需求,但至少这应该为您提供一个小的工作示例,展示一种可能的方法。

【讨论】:

    猜你喜欢
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    相关资源
    最近更新 更多