swift - Swift - 通过代码链接 UIViewController
问题描述
我正在尝试将编辑按钮链接回我的 UIViewController (AddfreshreleaseViewController)。当您向右滑动单元格时,此代码会在左侧显示编辑按钮,但是当我在“performSegue”中添加以尝试返回 UIViewController 时,应用程序会在我现在每次向编辑按钮滑动时崩溃。关于如何让这个工作的任何建议?
@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
let modifyAction = UIContextualAction(style: .normal, title: "Update", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
success(true)
})
modifyAction.title = "Edit"
modifyAction.backgroundColor = .blue
performSegue(withIdentifier: "addFreshRelease", sender: self)
return UISwipeActionsConfiguration(actions: [modifyAction])
}
这是我用于 FreshReleaseTableViewController 的代码:
import UIKit
import CoreData
import UserNotifications
class FreshReleaseTableViewController: UITableViewController{
var freshreleases = [Release_Date]()
let dateFormatter = DateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let button = UIButton.init(type: .custom)
//set image for button
button.setImage(UIImage(named: "Mic App Logo.png"), for: UIControlState.normal)
dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
//let button1 = UIButton()
//button1.addTarget(self, action: #selector(editAction), for: .touchUpInside)
//self.tableView.backgroundColor = UIColor.white
}
/* @objc func editAction() {
let viewController = AddfreshreleaseViewController()
navigationController?.present(viewController, animated: true, completion: nil)
}*/
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = Release_Date.fetchRequest() as NSFetchRequest<Release_Date>
let sortDescriptor1 = NSSortDescriptor(key: "artist", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "album", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
do {
freshreleases = try context.fetch(fetchRequest)
} catch let error {
print("Could not fetch because of error: \(error).")
}
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return freshreleases.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FreshReleaseCellIdentifier", for: indexPath)
let freshrelease = freshreleases[indexPath.row]
cell.textLabel?.numberOfLines = 0
let artist = freshrelease.artist ?? ""
let album = freshrelease.album ?? ""
cell.textLabel?.text = artist + "'s \nnew album '" + album + "'\nreleases"
if let date = freshrelease.release_date as Date? {
cell.detailTextLabel?.text = dateFormatter.string(from: date)
} else {
cell.detailTextLabel?.text = ""
}
return cell
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if freshreleases.count > indexPath.row {
let freshrelease = freshreleases[indexPath.row]
// Remove notification
if let identifier = freshrelease.release_dateId {
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [identifier])
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(freshrelease)
freshreleases.remove(at: indexPath.row)
do {
try context.save()
} catch let error {
print("Could not save \(error)")
}
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
let modifyAction = UIContextualAction(style: .normal, title: "Update", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
success(true)
})
modifyAction.title = "Edit"
modifyAction.backgroundColor = .blue
return UISwipeActionsConfiguration(actions: [modifyAction])
}
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
}
这是 AddfreshreleaseViewController 的代码:
import UIKit
import CoreData
import UserNotifications
class AddfreshreleaseViewController: UIViewController {
@IBOutlet var artisttextfield: UITextField!
@IBOutlet var albumtextfield: UITextField!
@IBOutlet var releasedatePicker: UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
releasedatePicker.minimumDate = Date()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func saveTapped( _ sender: UIBarButtonItem) {
let artist = artisttextfield.text ?? ""
let album = albumtextfield.text ?? ""
let releasedate = releasedatePicker.date
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newRelease = Release_Date(context: context)
newRelease.artist = artist
newRelease.album = album
newRelease.release_date = releasedate as NSDate?
newRelease.release_dateId = UUID().uuidString
if let uniqueId = newRelease.release_dateId {
print("The freshreleaseId is \(uniqueId)")
}
do {
try context.save()
let message = "\(artist)'s new album \(album) releases Today!"
let content = UNMutableNotificationContent()
content.body = message
content.sound = UNNotificationSound.default()
var dateComponents = Calendar.current.dateComponents([.month, .day],
from: releasedate)
dateComponents.hour = 09
dateComponents.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents,
repeats: true)
if let identifier = newRelease.release_dateId {
let request = UNNotificationRequest(identifier: identifier,
content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: nil)
}
} catch let error {
print("Could not save because of \(error).")
}
dismiss(animated: true, completion: nil)
print("Added a Release Date!")
print("Artist: \(newRelease.artist)")
print("Album: \(newRelease.album)")
print("Release Date: \(newRelease.release_date)")
}
@IBAction func cancelTapped(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
}
所以我想要做的是,当在 FreshReleaseTableViewController 中按下编辑按钮时,它会调出 AddfreshreleaseViewController。
但是,编辑按钮是用代码编写的,而不是实际上是条形按钮项。
更复杂的是,当用户访问 AddfreshreleaseViewController 时,他们将信息输入三个字段(艺术家、专辑和发布日期)并将其保存在 FreshReleaseTableViewController 中。因此,当 FreshReleaseTableViewController 中的编辑按钮将它们带回 AddfreshreleaseViewController 时,我需要将输入的用户信息(艺术家、专辑和发布日期)放在三个字段中,以便用户可以编辑这些字段,如果有的话初始输入错误。
解决方案
信息太少,但我会尝试猜测您遇到的行为。
尽管如此,为什么要在完成 modifyAction 时执行 Segue?您应该使用以下方法弹出当前视图控制器:
https://developer.apple.com/documentation/uikit/uinavigationcontroller/1621886-popviewcontroller
例子:
_ = navigationController?.popViewController(animated: true)
推荐阅读
- html - 反应式表单:在某些控件上用不同的功能替换回车键提交
- reactjs - 如何在 typescript 3 项目中使用 typescript 4 包?
- mysql - 连接两个 mySQL 表并使用唯一值进行汇总
- kubernetes - Kops 无法编辑节点实例类型
- azure-devops - Azure DevOps Pipeline - 服务连接权限
- objective-c - PHFetchOption 键的 NSPredicate 语法
- javascript - 我可以告诉汇总不要最小化它生成的代码吗?
- javascript - 如何在单击选择器之前在引导日期选择器中设置默认日期 10 年后
- python - 使用python维护目录中读取文件的顺序
- jquery - CSS过渡高度属性不起作用