繁体   English   中英

UIAlert视图从CustomCell类// Swift触发

[英]UIAlert view triggered from CustomCell Class // Swift

我有一个用CustomCells填充的TableViewCell。 在customCells中,我有一个要触发UIAlert的按钮。

这是CustomCell类中按钮的代码:

@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)
}

当我按下按钮时,得到以下警报: Warning: Attempt to present <UIAlertController: 0x7fc7f0cbc5c0> on <MyApp.TableViewController: 0x7fc7f0c965f0> whose view is not in the window hierarchy!

我在调试警报上做了一些研究,但是找不到迅速有效的答案,对我有用... ;-)

有任何想法吗?

THX // Seb

在您的TableViewController().presentViewController ,TableViewController()实际上创建了视图控制器TableViewController的新实例。 该实例不是当前在屏幕上显示的实例。 这就是为什么您会看到视图不属于窗口层次结构的错误。

为了解决此问题,将func anzahlButton(sender: UIButton)TableViewController文件,然后通过cellForRowAtIndexPath函数将其连接到按钮。 删除@IBAction部分,因为我们不再通过界面生成器连接按钮。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{
    // Your Code
    cell.button.addTarget(self, action: "anzahlButton:", forControlEvents: UIControlEvents.TouchUpInside)
}

然后换行

TableViewController().presentViewController(alert, animated: true, completion: nil)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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