I have a TableViewCell populated with CustomCells. In the customCells I have a button which I want to trigger an UIAlert.
Here is my code for the button in the CustomCell Class:
@IBAction func anzahlButton(sender: UIButton) {
let alert = UIAlertController(title: "Bitte gib Deine gewünschte Anzahl an:", message: nil, preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler {
(tf:UITextField!) in
tf.keyboardType = .NumberPad
tf.addTarget(self, action: "textChanged:", forControlEvents: .EditingChanged)
}
func handler(act:UIAlertAction!) {
let tf = alert.textFields![0] as UITextField
let addItem = "\(tf.text)"
var fixedToDoItems = ""
anzahlText.setTitle("\(addItem)", forState: .Normal)
//println("User entered \(addItem), tapped \(act.title)")
}
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: handler))
(alert.actions[1] as UIAlertAction).enabled = false
TableViewController().presentViewController(alert, animated: true, completion: nil)
}
When I hit the button I get this alert: Warning: Attempt to present <UIAlertController: 0x7fc7f0cbc5c0> on <MyApp.TableViewController: 0x7fc7f0c965f0> whose view is not in the window hierarchy!
I deed some resaerch on the debug-alert, but couldn't find an answer that is in swift and works for me... ;-)
Any ideas?
THX //Seb
In your line TableViewController().presentViewController
, TableViewController() actually creates a new instance of the view controller TableViewController
. This instance is not the one currently displayed on the screen. Which is why you get the error that the view is not part of the window hierarchy.
In order to fix that move the func anzahlButton(sender: UIButton)
to the TableViewController
file and then connect it to the button through cellForRowAtIndexPath
function. remove the @IBAction
part since we are no longer connecting the button through the interface builder.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
// Your Code
cell.button.addTarget(self, action: "anzahlButton:", forControlEvents: UIControlEvents.TouchUpInside)
}
Then change the line
TableViewController().presentViewController(alert, animated: true, completion: nil)
to
self.presentViewController(alert, animated: true, completion: 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.