【问题标题】:How to substitute string name from a struct with its corresponding image name?如何用相应的图像名称替换结构中的字符串名称?
【发布时间】:2016-12-23 17:34:34
【问题描述】:

我有一个结构来存储已经捆绑在应用程序中的图片的名称和图像名称,如下所示

struct City { var name: String
              var imageName: String }

class firstViewController: UIViewController

let cities = [City(name:"City00", imageName:"city_00"),
              City(name:"City01", imageName:"city_01"),
              City(name:"City02", imageName:"city_02")]

在 displayViewController 中,我有一个变量 nowCityImages 来存储从 firstViewcontroller 中选择的数据

class displayViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {

var nowCityImages: [String] = []

现在我想在 tableview 中显示城市的图像

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let myCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CityCell

    let outCityImages = nowCityImages[indexPath.item]

    // This is not displaying any images
     myCell.cityImage.image = UIImage(named:outCityImages)

   return myCell
}

如果我使用print(outCityImages),我会得到以下输出作为例外

City00
City02

但我不知道如何在 tableview 单元格中替换 City00 with city_00City02 with city_02 以便显示图像。

【问题讨论】:

  • @JimmyJames,这个问题是用来搜索的,我正在寻找替代
  • 检查您向 nowCityImages 添加或附加字符串的语句。它应该类似于 city.imageName 而不是 city.name。例如nowCityImages.append(cities[0].imageName)

标签: swift uitableview struct


【解决方案1】:

如果末尾的数字是2位长度:

var str = "City00"
let index = str.index(str.endIndex, offsetBy: -2)

var str1 = str.substring(to: index).lowercased()
var str2 = str.substring(from: index)
let name = "\(str1)_\(str2)" //city_00

【讨论】:

  • 并非总是如此,我只是举了一个例子来说明我的问题。我想知道如何用他们的图像名称替换我得到的城市的相应名称。
  • displayViewController中只有城市名。我认为您可能会将 City 对象/imageName 传递给 displayViewController 而不仅仅是城市名称,或者创建一个方法来通过城市名称获取城市对象。
【解决方案2】:

你能不能把nowCityImages的代码改成这个

    var nowCityImages: [String] = cities.filter(){$0.imageName}

现在它会根据需要返回图像名称。

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 2014-10-26
    • 2021-12-26
    • 2022-07-29
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多