ios - Swift:如何在 plist 中获取数组的第一个字符串?

标签 ios arrays swift plist

我有一个 plist,它是一个包含数百个数组的数组,每个数组包含 22 个字符串。如何获取 plist 中每个数组的第一个字符串?

我正在使用集合,在 cellForItemAt 中,我试图让数组的第一个字符串显示在标签中的每个单元格下。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Collections

    // Set Image
    cell.imageCell.image = UIImage(named: "image_\(indexPath.row)")

    // Check NameLabel Switch Status
    if savedSwitchStatus == true {

        cell.labelCell.isHidden = false
        cell.labelCell.text = (??) // <--------------

    } else {
        cell.labelCell.isHidden = true
    }

    return cell
}

我有两种类型的 plist:

第一个 plist 有 1 个包含多个字符串的数组。每个字符串都是单元格下方的名称。 plist1

第二个 plist 是一个数组数组,每个数组包含 22 个字符串。在这里,我只需要从每个数组中获取第一个字符串以显示在单元格下方。 plist2 plist2_1

最佳答案

您需要将您的 plist 解析为字符串数组的数组,即 [[String]]。

func arrayFromPlist(plist:String) -> [[String]]? {
    guard let fileUrl = Bundle.main.url(forResource: plist, withExtension: "plist"), let data = try? Data(contentsOf: fileUrl) else {
        return nil
    }

    return try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String]]
}

使用上面的函数获取数组并将该数组用作tableview的数据源。

var datasourceArray:[[String]] {
    didSet {
        self.tableView.reloadData()
    }
}

在你的 cellForRow 中:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Collections

    // Set Image
    cell.imageCell.image = UIImage(named: "image_\(indexPath.row)")
    let strings = datasourceArray[indexPath.row]!
    // Check NameLabel Switch Status
    if savedSwitchStatus == true {

        cell.labelCell.isHidden = false
        cell.labelCell.text = strings.first

    } else {
        cell.labelCell.isHidden = true
    }

    return cell
}

关于ios - Swift:如何在 plist 中获取数组的第一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47342811/

相关文章:

objective-c - ALAssetsGroup setAssetsFilter 在iOS中同时获取照片和视频

ios - GLSL 中的反射贴图

ios - 如何测试在 viewcontroller 单元测试中设置私有(private)变量的方法?

swift - 无法将按钮焦点移动到下一行

ios - 多个 NSURLSession 导致 UITableView 问题

ios - 以编程方式快速将搜索栏添加到 TableView

c - 数组在循环中如何工作?

java - 复制数组或强制 ArrayList 指定初始大小。什么更有效?

javascript - 重构DOM搜索方法?

ios - 检索 Firebase 数据的更有效方法?