简体   繁体   中英

UIAlertController in tableViewCell - Swift

I have a button in each cell in a tableviewcell . When the button is clicked, in the cell coding page I had an action which was working already. However I decided to let users confirm it before the action starts, so added an UIAlertController inside the action. The alert controller works fine in a UIviewcontroller , but in a UItableviewcell with the code below I got the error message: "does not have a member named presentviewcontroller ". How can I make it work? My code is here. Thanks

@IBAction func followBtn_click(sender: AnyObject) {



        if title == "Following" {

            var refreshAlert = UIAlertController(title: "Sure?", message: "Do you want to unfollow this person?", preferredStyle: UIAlertControllerStyle.Alert)
            refreshAlert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (action: UIAlertAction!) in

            var query = PFQuery(className: "follow")

            query.whereKey("user", equalTo: PFUser.currentUser()!.username!)
            query.whereKey("userToFollow", equalTo: usernameLbl.text!)

            var objects = query.findObjects()

            for object in objects! {

                object.delete()

            }

            }))

            refreshAlert.addAction(UIAlertAction(title: "No", style: .Default, handler: { (action: UIAlertAction!) in
                println("Cancel unfollow")
            }))

            self.presentViewController(refreshAlert, animated: true, completion: nil)

         /*  self.window?.rootViewController?.presentViewController(refreshAlert, animated: true, completion: nil)

            when I use the above to make it run, the code runs but nothing happens and I get the warning below in the output area

             2015-07-02 08:57:22.978 MyLast[968:200872] Warning: Attempt to present <UIAlertController: 0x7f849c04ed20> on <UINavigationController: 0x7f8499c69020> whose view is not in the window hierarchy!



          */



        }

        else {

            println(“rest will work”)
           /*   rest of the code */

        }


}

Make sure your tableview controller is in hierarchy of navigation controller or embed in UINavigationController. Because UIAlertView is deprecated in swift And there is a UIAlertViewController and whenever you require or to present Alert you must have a Controller Hierarchy.

You also can show ActionSheet using same code by little changes UIAlertControllerStyle is action sheet.

One another suggestions is once try with remove your handler code to nil

alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM