【问题标题】:Swift UITableview display data from arraySwift UITableview 显示数组中的数据
【发布时间】:2015-03-14 18:23:44
【问题描述】:

我有一个 API 可以根据用户返回一串数字。 一旦发出 API 请求,该函数就会将数字放入一个数组中。

var usernumbers = userResponse["Numbers"] as NSArray

调试器 PrintLn 显示:

( 16467621007, 14152555613, 14046206007 )

当我把它交给 UITableView 时,我如何拆分数组以便每个数字进入一个单独的单元格? 我试过了:

let rowData: NSArray = tableData (usernumbers has been handed to table data)

我试过了:

cell.textLabel?.text = rowData.row (and all varieties of)

我哪里错了?

【问题讨论】:

  • 你能展示你的 cellForRowAtIndexPath 和 numberOfRowsInSection 方法的实现吗?你应该会收到来自rowData.row 的错误,因为 NSArray 没有row 属性。

标签: ios arrays uitableview swift


【解决方案1】:

如果我正确理解您的问题,这就是您要找的,

cell.textLabel?.text = rowData[indexPath.row] as String

编辑:

let numberValue : NSNumber = rowData[indexPath.row] as NSNumber

 let text : String = numberValue.stringValue // add  nil check

 cell.textLabel?.text = text 

你可以直接赋值

cell.textLabel?.text = numberValue.stringValue - 如果您确定不会有 nil

【讨论】:

  • 当我使用 'rowData[indexPath.row] as String' 我得到“Swift 动态转换失败”,所以我没有正确地从数组转换成字符串。
  • 目前func tableView代码为: let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell") let rowData: NSArray = tableData cell.textLabel?.text = rowData[indexPath .row] 作为字符串返回单元格,该单元格因“Swift 动态转换失败”错误而失败
【解决方案2】:

使用rowData[indexPath.row],其中indexPath.row是从0开始的当前单元格

【讨论】:

    【解决方案3】:
     private let data = Array(1...9)
    

    那么……

     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return data.count
     }
    

    在你的:

        func tableView(tableView: UITableView, cellForRowAtIndexPath 
        indexPath: NSIndexPath) -> UITableViewCell {...
    

    所有常见的东西。

      cell.textLabel?.text = String(format: "the magic number is : %.f", data[indexPath.row])
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 2012-08-10
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多