【问题标题】:uitableview cell cellForRowAtindexPath fetch first letter pick from name in swift3uitableview 单元格 cellForRowAtindexPath 从 swift3 中的名称中提取第一个字母
【发布时间】:2017-11-23 05:58:14
【问题描述】:

我的 UITableView 有一个自定义单元格,我将显示项目名称的第一个字符like this"below image"

所以我的问题是如何创建它如何从通过 json 获取的名称数据中提取第一个字母。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ProjectTabTableViewCell
   cell.colorViewOutlet.layer.cornerRadius = 25.0
    let projectLst = projectList[indexPath.row]



    let str = projectLst.NameEN



    print(str?.characters.first?.description ?? "");
    projectNameFirst = [str?.characters.first?.description ?? ""]
    print(projectNameFirst)
    cell.wordsLabel?.text = projectNameFirst[indexPath.row]

    cell.nameLabel?.text = projectLst.NameEN
    cell.colorViewOutlet.backgroundColor = .random

    return cell
}

【问题讨论】:

  • 请说清楚。
  • 你能分享你的 JSON 和代码吗..
  • 第一个字母和名字有什么关系?在图像中似乎没有关系。

标签: ios json swift uitableview uilabel


【解决方案1】:
  let stringInput = "Ramu"
  let stringInputArr = stringInput.components(separatedBy: " ")
  var stringNeed = ""

  for string in stringInputArr {
       stringNeed = stringNeed + String(string.characters.first!)
  }

  print(stringNeed)

【讨论】:

  • ganesh 当我附加结果标签单元格“cell.wordsLabel?.text = result[indexPath.row]”,xcode 给我错误“下标”不可用:不能用 Int 下标字符串,请参阅文档评论进行讨论
【解决方案2】:

要从字符串中获取第一个字符,请使用以下代码

let str = "\(projectLst.NameEN)"
var result = ""
if str.characters.count > 0{
  result = String(str.characters.prefix(1)) // which will return your first charcter
 } else {
  result = "" // result will be empty if string is empty
 }
 cell.wordsLabel?.text = result

希望对你有帮助

【讨论】:

  • ganesh 但是当我将结果值附加到我的 tableview 单元格标签 xcode 给我这种类型的错误“下标”不可用:不能用 Int 下标字符串,请参阅“我现在能做什么?
  • 根据您的需要更新,希望能解决您的问题
  • ganesh 当我附加结果标签单元格“cell.wordsLabel?.text = result[indexPath.row]”,xcode 给我错误“下标”不可用:不能用 Int 下标字符串,请参阅文档评论以进行讨论 ..
  • 您需要将结果值设置为标签,结果将是字符串而不是数组答案更新检查一次
  • 我很乐意提供帮助:)
猜你喜欢
  • 2011-10-09
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多