我有一个简单的表格单元格,其中包含一些按英文字母顺序排列的名称。 我设法将所有内容本地化为其他语言,并且一切正常。 问题是:是否有一种方法或命令可以将其他语言的本地化名称按字母顺序排列?
import UIKit
var animals = [“A1”, “A2”, “A3”, “A4”, “A5”];
class TableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return animals.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellController;
cell.textLabel?.font = UIFont(name: "Futura-Bold", size: 18);
cell.textLabel?.textColor = UIColor.black;
cell.textLabel?.text = NSLocalizedString(animals[indexPath.row], comment: "");
cell.smallBird.image = UIImage(named: animals[indexPath.row] + ".png");
return cell
}
}
本地化字符串
/* Animals (EN) */
“A1" = “Cat”;
“A2" = “Dog”;
“A3" = “Owl”;
“A4" = “Leon”;
“A5" = “Tiger”;
最佳答案
您目前按键而不是值对它们进行排序。
由于您需要图像的键和标签的值,并且您希望按值对行进行排序,因此您需要的不仅仅是键数组。
以下创建一个键和本地化名称元组数组,按本地化名称排序。
let animals = ["A1", "A2", "A3", "A4", "A5"].map { ($0, NSLocalizedString($0, comment: "")) }.sorted { $0.1 < $1.1 }
然后更新cellForRowAt
:
cell.textLabel?.text = animals[indexPath.row].1
cell.smallBird.image = UIImage(named: animals[indexPath.row].0)
使用 UIImage(named:)
时不需要添加“.png”。
关于ios - 所有可本地化字符串的字母顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47641323/