首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >创建数组并将元素分配给UITableViewCell并将其带回labelText元素时遇到的问题

创建数组并将元素分配给UITableViewCell并将其带回labelText元素时遇到的问题
EN

Stack Overflow用户
提问于 2014-10-31 05:51:24
回答 1查看 40关注 0票数 0

正如标题所示,我有以下代码:

代码语言:javascript
运行
复制
// Playground - noun: a place where people can play

import UIKit

var placesTableCells:[UITableViewCell] = []
var temporalCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
for i in 0...10 {
    temporalCell?.textLabel?.text = "ola k ace \(i)"
    placesTableCells.append(temporalCell!)
    println(placesTableCells[i].textLabel!.text!)
}
println()
for i in 0...10 {
    println(placesTableCells[i].textLabel!.text!)
}

当我在for循环中请求placesTableCells时,所有操作都很好,它会打印:

代码语言:javascript
运行
复制
ola k ace 0
ola k ace 1
ola k ace 2
ola k ace 3
ola k ace 4
ola k ace 5
ola k ace 6
ola k ace 7
ola k ace 8
ola k ace 9
ola k ace 10

但是当我请求它的数组时,它只返回"ola 10“十次,它打印:

代码语言:javascript
运行
复制
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10

问题在哪里?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-31 05:57:36

我相信这是因为您在for循环之外声明了temporalCell,并且每次在循环中都会更改它的值,这也会改变数组中以前引用对象的值。

如果希望在数组中添加不同的对象,请将temporalCell声明移到for循环中,如下所示

代码语言:javascript
运行
复制
var placesTableCells:[UITableViewCell] = []
for i in 0...10 {
    var temporalCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
    temporalCell.textLabel?.text = "ola k ace \(i)"
    placesTableCells.append(temporalCell)
    println(placesTableCells[i].textLabel!.text!)
}
println()
for i in 0...10 {
    println(placesTableCells[i].textLabel!.text!)
}

而且它应该能工作。让我知道。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26668295

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档