在表格视图单元格上添加标签文本

时间:2016-08-18 14:01:57

标签: ios swift uitableview uilabel tableviewcell

如何将标签转换为整数并将所有标签加起来

    var totalCount:Int?
    if let number = Int(price.text!) {
        let myNumber = NSNumber(integer:number)
        totalCount = totalCount! + myNumber.integerValue
        print(totalCount)
    } else {
        print("'\(price.text)' did not convert to an Int")
    }

这是我的代码无效

2 个答案:

答案 0 :(得分:2)

使用此方法。

var totalCount = 0
guard let priceString = price.text else {
   print("price label is nil")
   return
}
let myNumber = Int(priceString)
totalCount = totalCount + myNumber!
print(totalCount)

答案 1 :(得分:0)

兄弟我首先尝试了你的编码,它显示了在这一行上运行时的错误

totalCount = totalCount! + myNumber.integerValue
  

致命错误:在解包可选值时意外发现nil

然后我设置

var totalCount:Int = 0
var arr = [String]()

尝试过的样本编码是

override func viewDidLoad()
{
   super.viewDidLoad()
   var totalCount:Int = 0
   let priceValue: String = "100"
   arr.append(priceValue)
   self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

}

然后在tableView委托方法

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{
    let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!

    let priceVal = arr[indexPath.row]
    if let number = Int(priceVal)
    {
        let myNumber = NSNumber(integer:number)
        totalCount =  totalCount  + myNumber.integerValue
        print(totalCount)
    }
    else
    {
       print("'\(priceVal)' did not convert to an Int")
    }

    cell.textLabel?.text = String(totalCount)

    return cell
}

印刷结果

100

Community wiki group answered