我的目标是在主视图的表中创建一个新行,标题为存储在 namePrompt
中的 UIAlert 的输入。我将如何实现这一点?
目前,当我尝试创建一个新行时(使用 iPad 模拟器右上角的 +
按钮,运行 iOS 8)它使应用程序崩溃。我不太确定我做错了什么,非常感谢任何帮助。
代码:
func insertNewObject(sender: AnyObject) {
//prompt for kid name
var namePrompt = UIAlertController(title: "Add Child", message: "Please enter child name", preferredStyle: UIAlertControllerStyle.Alert)
namePrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
namePrompt.addAction(UIAlertAction(title: "Add Child", style: UIAlertActionStyle.Default, handler: nil))
namePrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
textField.placeholder = "Johnny"
})
self.presentViewController(namePrompt, animated: true, completion: nil)
let childName: AnyObject = namePrompt.textFields![0]
//add new object w/ above name
objects.insertObject(childName, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
我认为问题出在 let childName: Any Object
行和/或 objects.insertObject
行。
--编辑--
当我构建/运行项目时,代码中没有出现错误,但是当我尝试添加新行时,只要按下 +
按钮,我就会得到 0x1fbaff4: nopw %cs:(%eax,%eax)
来自 Thread 1
。这与 let object = objects[indexPath.row] as NSDate
行相关(在下面的代码片段中)行(上面 objects.insertObject
行的默认值是一个 NSDAte ).我将 NSDate
更改为 NSString
,同样的事情发生了。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let object = objects[indexPath.row] as NSString
cell.textLabel?.text = object.description
return cell
}
最佳答案
您似乎假设 UIAlertController 的文本字段将在出现警报后立即填充。这不会给用户任何时间来实际填写字段。
改为将 let childName = namePrompt.textFields![0]
行(及后续行)放在您的一个按钮操作中,并等待用户在阅读文本字段之前点击该按钮。
--编辑--
这是您的代码以及我建议的修改。我尽可能少地更改您的代码。请注意,有一个 if 语句可以防止空的 childNames,但它不能防止有人输入一堆空格。您可能应该使该部分更健壮。
func insertNewObject(sender: AnyObject) {
//prompt for kid name
var namePrompt = UIAlertController(title: "Add Child", message: "Please enter child name", preferredStyle: UIAlertControllerStyle.Alert)
namePrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
namePrompt.addAction(UIAlertAction(title: "Add Child", style: UIAlertActionStyle.Default, handler: { (alertAction) in
let childName = (namePrompt.textFields![0] as UITextField).text as String
if childName != "" {
self.objects.insert(childName, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}))
namePrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
textField.placeholder = "Johnny"
})
self.presentViewController(namePrompt, animated: true, completion: nil)
}
关于ios - 带有/文本字段的 UIAlert 到表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26436452/