gpt4 book ai didi

Swift - 通过代码链接 UIViewController

转载 作者:行者123 更新时间:2023-11-28 14:26:06 25 4
gpt4 key购买 nike

我正在尝试将编辑按钮链接回我的 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呢?你应该使用这个弹出当前 View Controller :

https://developer.apple.com/documentation/uikit/uinavigationcontroller/1621886-popviewcontroller

例子:

 _ = navigationController?.popViewController(animated: true)

关于Swift - 通过代码链接 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51524469/

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