gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:12:58 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com