我创建了一个自定义按钮,以便在按钮中包含我所需的信息:
class CustomButton: UIButton {
var urlString: String?
var documentType: String?
var requestEntity: String?
var requestSortBy: [NSSortDescriptor]?
var requestPredicate: NSPredicate?
}
当我在collectionView(嵌入在tableView中)中创建单元格时,我会在我的自定义按钮documentTypeButton
中包含信息。还要设置执行函数HomeTableViewController.documentTypeButtonTapped(_:)
的目标以执行segue。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let languageSelected = UserDefaults().value(forKey: "language") as! String
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "allDocumentsItemCell", for: indexPath) as! AllDocumentsCollectionViewCell
cell.documentTypeButton.documentType = Catalog.sharedInstance.allSections[allDocumentsSection!].singleItems[indexPath.row].name
cell.documentTypeButton.requestEntity = Catalog.sharedInstance.allSections[allDocumentsSection!].singleItems[indexPath.row].entityName
cell.documentTypeButton.requestSortBy = Catalog.sharedInstance.allSections[allDocumentsSection!].singleItems[indexPath.row].sortBy
cell.documentTypeButton.requestPredicate = Catalog.sharedInstance.allSections[allDocumentsSection!].singleItems[indexPath.row].predicate
cell.documentTypeButton.addTarget(nil, action: #selector(HomeTableViewController.documentTypeButtonTapped(_:)), for: .touchUpInside)
return cell
}
在HomeTableViewController
中,当触摸按钮时,我有一个执行函数:
@objc func documentTypeButtonTapped(_ sender: CustomButton) {
performSegue(withIdentifier: "goToDocumentList", sender: CustomButton())
print(sender.documentType)
print(sender.requestEntity)
}
func prepare(for segue: UIStoryboardSegue, sender: CustomButton) {
let languageSelected = UserDefaults().value(forKey: "language") as! String
if let destination = segue.destination as? DocumentListTableViewController {
destination.titlePassed = sender.documentType!.localized(lang: languageSelected)
destination.requestedEntity = sender.requestEntity
destination.requestedSortBy = sender.requestSortBy
destination.requestedPredicate = sender.requestPredicate
}
}
上述打印语句能够正常输出信息。并且segue转到了DocumentListTableViewController
。
在DocumentListTableViewController
的viewDidLoad
中,我添加了以下内容:
override func viewDidLoad() {
super.viewDidLoad()
print(titlePassed)
print(requestedEntity)
}
这两个打印语句会打印出nil
。
我猜问题应该在prepareForSegue
方法中,可能和发送者有关... 我不知道。
任何帮助都将不胜感激。