我希望通过按按钮对表格单元格进行排序。我现在所拥有的目前无法正常工作。当我按下按钮时没有任何效果。我只想要当用户按下func sortA时tableview遵循排序算法。运行此代码时没有发现错误。
var itemName2 : [NSManagedObject] = []
@objc func sortA(sender: UIButton){
let appD = UIApplication.shared.delegate as! AppDelegate
let context = appD.persistentContainer.viewContext
//check with Golf App
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Data")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "hits", ascending: true),NSSortDescriptor(key: "atBATS", ascending: true)]
do {
itemName2 = try context.fetch(fetchRequest)
self.theScores.reloadData()
}catch {
print("Ashley Tisdale")
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let title = itemName[indexPath.row]
let cell = theScores.dequeueReusableCell(withIdentifier: "MyCell", for : indexPath)
cell.textLabel!.numberOfLines = 2
cell.selectionStyle = .default
cell.textLabel?.textAlignment = .center
cell.layoutMargins = UIEdgeInsets.zero
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
let attr1 = title.value(forKey: "a") as? String
let attr2 = title.value(forKey: "b") as? String
let text = [" ",attr2," : ", attr1].compactMap { $0 }.reduce("", +)
cell.textLabel?.text = "Game \(indexPath.row+1) \(text)"
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
sort.addTarget(self, action:#selector(sortA), for: .touchDown)
}