繁体   English   中英

Swift:在表视图单元格中创建UILabel

[英]Swift: Create UILabel in Table View Cell

我有一个表视图控制器,其中声明了以下数组:

var newData = [String]()

在我的viewDidLoad函数中,我具有以下内容:

newData = ["1", "2", "3"]

我正在尝试在表格单元格内创建UILabel对象。 到目前为止,我的cellForRowAtIndexPath函数中包含以下内容:

let cell = tableView.dequeueReusableCellWithIdentifier("TableCell", forIndexPath: indexPath) as UITableViewCell

//Programmatically create label
var newLabel = UILabel(frame: CGRectMake(280.0, 14.0, 300.0, 30.0))
newLabel.tag = 1
newLabel.font = UIFont(name: "Avenir", size: 17.0)
newLabel.textColor = UIColor.darkGrayColor()

cell.addSubview(newLabel)
cell.contentView.viewWithTag(1) = newData[indexPath.row] //This is where I get the error

但是,出现以下错误:“无法分配给该表达式的结果”。 在Objective-C中,我将其编写为:

[(UILabel *)[cell.contentView viewWithTag:1] setText:[newData objectAtIndex:indexPath.row]];

我的问题是:如何在Swift中编写上一行代码? 预先感谢您的回复。

分配文本最简单正确的方法是,在那时创建标签分配文本

var newLabel = UILabel(frame: CGRectMake(280.0, 14.0, 300.0, 30.0))
newLabel.text = newData[indexPath.row]
newLabel.tag = 1

迅捷3

var newLabel = UILabel(frame: CGRect(x: 280.0, y: 14.0, width: 300.0, height: 30.0))
newLabel.text = newData[indexPath.row]
newLabel.tag = 1

编辑

即使您想使用viewWithTag方法,也必须通过类型转换以这种方式使用它

var lbl : UILabel? = cell.contentView.viewWithTag(1) as? UILabel
lbl?.text = newData[indexPath.row]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM