【问题标题】:Add label text on table view cell [closed]在表格视图单元格上添加标签文本[关闭]
【发布时间】:2023-03-21 06:57:02
【问题描述】:

如何将标签转换为整数并将它们全部相加

    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")
    }

这是我的代码,它不起作用

【问题讨论】:

  • 您不能将标签转换为整数。如果您在文本中获取数字,则可以将标签文本转换为整数。
  • 你在哪一行遇到这个问题
  • 让 output = Int(price.text!) print (output) - 是转换
  • @user3182143 是的,我说的是文本
  • @Anbu.Karthik 这不会把它们加起来只会打印出来

标签: ios swift uitableview uilabel tableviewcell


【解决方案1】:

使用这个方法。

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

【讨论】:

  • 我仍然将每个单元格文本分别打印出来我想得到所有内容的总和
  • 您的意思是在表格视图中?并请向我展示您想要汇总的完整源代码。
  • 这里是代码pastebin.com/hXsCDC0d
  • 我访问了你的代码,顺便说一句,你想要什么结果?
  • 我想通过将每个单元格的价格相加得到总价
【解决方案2】:

兄弟,我先尝试了您的编码,它在此行运行时向我显示了错误

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

【讨论】:

  • 是的,这会起作用,但我有不止一个单元格,所以不止一个文本
  • 将字符串对象添加到数组中
  • 你能更新你的答案吗
  • lordxxx你用tableview吗?
  • 是的,我使用 tableview
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
相关资源
最近更新 更多