Я работаю над приложением, которое имеет TableViewCells в трех сценах. Я хотел бы заполнить с помощью AlertBox, чтобы взять «постучал элемент» и передать эти данные в TableViewCell в другой сцене ..
Вот первая сцена, в которой у меня есть alertBox
class SupplementScene: UIViewController, UITableViewDataSource,
UITableViewDelegate
{
@IBOutlet weak var lblSupplement: UILabel!
@IBOutlet weak var sbSupplement: UISearchBar!
@IBOutlet weak var tvSupplement: UITableView!
let stackScene = StackScene()
var suppArray:[Supplement] = [Supplement]()
var stackArray:[Stack] = [Stack]()
let cellReuseIdentifier = "cell1"
var count:Int = 0
// create the managed object context
// it is used for CoreData. Must be created in the ViewController
let managedObjectContext = (UIApplication.shared.delegate
as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
applyDesign()
tvSupplement.dataSource = self
tvSupplement.delegate = self
suppArray = CoreDataHandler.getAllSupplementObjects(managedObjectContext: managedObjectContext)
}
// functions from the protocols
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return suppArray.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// create a new cell if needed or reuse an old one
// had to change cell to cell1 since identified was used before
let cell:SupplementTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! SupplementTableViewCell!
// set the text from the array into the cells labels
cell.lblName.text = suppArray[indexPath.row].name
cell.backgroundColor = UIColor.darkGray
cell.lblName.textColor = UIColor.white
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
// print("You tapped cell number \(indexPath.row).")
// get the tableViewCell
let cell = tableView.cellForRow(at: indexPath) as! SupplementTableViewCell
// print the text property in the label in the tableViewCell
print("TableView tapped = \(cell.lblName.text!)")
updateStack(name: cell.lblName.text!)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// update function
func updateStack(name:String)
{
// get the objectby name
_ = CoreDataHandler.getSupplementByName(managedObjectContext: managedObjectContext, name: name)!
// create an Alert with a textFields for all ContactBusiness fields
let alertController = UIAlertController(title: "Udpate \(name)",
message: "",
preferredStyle: UIAlertControllerStyle.alert)
// create a default action for the Alert
let defaultAction = UIAlertAction(
title: "Ok",
style: UIAlertActionStyle.default,
handler: {(alertAction: UIAlertAction!) in
// get the input from the alert controller
// put the user updated fields back in the contactBusiness object
// save the managedObject
CoreDataHandler.addStackObject(managedObjectContext: self.managedObjectContext)
// get all Contacts from CoreData
self.stackArray = CoreDataHandler.getAllStackObjects(managedObjectContext: self.managedObjectContext)
// reload the data into the TableView
self.tvSupplement.reloadData()
self.stackScene.tvStack.reloadData()
})
let cancelAction = UIAlertAction(
title: "Cancel",
style: UIAlertActionStyle.cancel,
handler:nil)
// add the action to the Alert
alertController.addAction(defaultAction)
alertController.addAction(cancelAction)
// display the Alert
present(alertController, animated: true, completion: nil)
}
}
и теперь класс, из которого я хочу получить данные.
class StackScene: UIViewController, UITableViewDelegate,
UITableViewDataSource
{
@IBOutlet weak var lblStack: UILabel!
@IBOutlet weak var sbStack: UISearchBar!
@IBOutlet weak var tvStack: UITableView!
let cellReuseIdentifier = "cell3"
var stackArray:[Stack] = [Stack]()
// var suppArray:[Supplement] = [Supplement]()
var count : Int = 0
// create the managed object context
// it is used for CoreData. Must be created in the ViewController
let managedObjectContext = (UIApplication.shared.delegate
as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
tvStack.delegate = self
tvStack.dataSource = self
stackArray = CoreDataHandler.getAllStackObjects(managedObjectContext: managedObjectContext)
// doing this to apply the design changes to the app
applyDesign()
}
// functions from the protocols
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return stackArray.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// create a new cell if needed or reuse an old one
// had to change cell to cell1 since identified was used before
let cell:StackTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell3") as! StackTableViewCell!
// set the text from the array into the cells labels
cell.lblName.text = stackArray[indexPath.row].name
cell.backgroundColor = UIColor.darkGray
cell.lblName.textColor = UIColor.white
return cell
}
@IBAction func longPressDelete(_ sender: UILongPressGestureRecognizer)
{`enter code here`
// get the location of the long press in the table
// location returns a CGPoint
let p = sender.location(in: tvStack)
// get indexPath at location of the long press
let indexPath = tvStack.indexPathForRow(at: p)
// if nil, selected the table, not a row
// if not nil, check for long touch began.
// we are not interested in the long touch ended
if indexPath == nil
{
print("Long press on table view, not row.")
}
else if (sender.state == UIGestureRecognizerState.began)
{
// get the tableViewCell
let cell = tvStack.cellForRow(at: indexPath!) as! StackTableViewCell
print("TableView LongPress = \(cell.lblName.text!), Pos: \(indexPath!.row)")
// call the deleteContact function
deleteContact(name: cell.lblName.text!, position: indexPath!.row)
// do something for long press here
}
else if(sender.state == UIGestureRecognizerState.ended)
{
print("Long press ended")
}
}
// function to display alert and confirm deletion
func deleteContact(name:String, position:Int)
{
// create the AlertController
let alertController = UIAlertController(title: "Delete",
message: name + ": Confirm Delete",
preferredStyle: UIAlertControllerStyle.alert)
// create a default action button
let deleteAction = UIAlertAction(title: "Delete",
style: UIAlertActionStyle.default,
handler: {(alertAction: UIAlertAction!) in
// remove from array
self.stackArray.remove(at: position)
// reload the tableView
self.tvStack.reloadData()
// remove from CoreData
CoreDataHandler.deleteStackByName(managedObjectContext: self.managedObjectContext, name: name)
})
// Alerts can only have one cancel action
// It is bolded and always comes last
let cancelAction = UIAlertAction(title: "Cancel",
style: UIAlertActionStyle.cancel,
handler: nil)
// Add the actions to the Alert
alertController.addAction(deleteAction)
alertController.addAction(cancelAction)
// present or display the Alert
present(alertController, animated: true, completion: nil)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Я знаю, что не использую segue для выполнения транзакций такого типа. Но я искал эти темы и Google для любой информации, и я пытаюсь найти лучшее решение для этого. AlertBox выскакивает и имеет постучавший элемент в textField, но я не могу получить данные из этого alertBox textField для заполнения в TableViewCell класса «stack».
Дайте мне знать, если есть какая-либо другая информация, которую я могу предоставить. Я все еще учу Свифта.