【问题标题】:Swift: Create UILabel in Table View CellSwift:在表格视图单元格中创建 UILabel
【发布时间】:2014-11-09 02:18:28
【问题描述】:

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

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 中编写前面的代码行?提前感谢您的回复。

【问题讨论】:

    标签: ios arrays uitableview swift uilabel


    【解决方案1】:

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

    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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2018-02-26
      相关资源
      最近更新 更多