在Swift中刷新基于Int的UITableView的某一行

Sen*_*con 75 uitableview nsindexpath ios swift

我是Swift的初级开发人员,我正在创建一个包含UITableView的基本应用程序.我想使用以下方法刷新表格的某一行:

self.tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: UITableViewRowAnimation.none)
Run Code Online (Sandbox Code Playgroud)

我希望刷新的行来自一个名为rowNumber的Int

问题是,我不知道如何做到这一点,我搜索的所有线程都是Obj-C

有任何想法吗?

Lyn*_*ott 174

您可以NSIndexPath使用行和节号创建一个,然后重新加载它,如下所示:

let indexPath = NSIndexPath(forRow: rowNumber, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我假设您的表只有一个部分(即0),但您可以相应地更改该值.

Swift 3.0的更新:

let indexPath = IndexPath(item: rowNumber, section: 0)
tableView.reloadRows(at: [indexPath], with: .top)
Run Code Online (Sandbox Code Playgroud)


Ale*_*ano 20

对于软影响动画解决方案:

斯威夫特3:

let indexPath = IndexPath(item: row, section: 0)
tableView.reloadRows(at: [indexPath], with: .fade)
Run Code Online (Sandbox Code Playgroud)

Swift 2.x:

let indexPath = NSIndexPath(forRow: row, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
Run Code Online (Sandbox Code Playgroud)

这是保护应用免受崩溃的另一种方法:

斯威夫特3:

let indexPath = IndexPath(item: row, section: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.index(of: indexPath as IndexPath) {
    if visibleIndexPaths != NSNotFound {
        tableView.reloadRows(at: [indexPath], with: .fade)
    }
}
Run Code Online (Sandbox Code Playgroud)

Swift 2.x:

let indexPath = NSIndexPath(forRow: row, inSection: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.indexOf(indexPath) {
   if visibleIndexPaths != NSNotFound {
      tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
   }
}
Run Code Online (Sandbox Code Playgroud)


Neh*_*eha 7

雨燕4

let indexPathRow:Int = 0    
let indexPosition = IndexPath(row: indexPathRow, section: 0)
tableView.reloadRows(at: [indexPosition], with: .none)
Run Code Online (Sandbox Code Playgroud)