如何使用AlertBox和CoreData从两个UITableViewCells传递数据?

时间:2018-05-06 21:34:52

标签: ios swift uitableview core-data

我正在开发一个在三个场景中有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来执行此类交易。但我搜索了这些主题和谷歌搜索任何信息,我正在努力解决这个问题的最佳解决方案。 alertBox弹出并在textField中有tapped项目,但是我无法从该alertBox textField获取数据以填充到“stack”类的TableViewCell中。

如果我能提供任何其他信息,请告诉我。我还在学习斯威夫特。

0 个答案:

没有答案