[英]Defining UIAlert in a separate class file, then invoking it from any view controller
[英]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.