我正在尝试让UIAlertController接受来自用户的文本,并将用户的输入设置为表视图的第一个单元格的标签。
var objects = [AnyObject]()
func insertNewObject(sender: AnyObject) {
var alert = UIAlertController(title: "New Routine", message: "", preferredStyle: UIAlertControllerStyle.Alert)
var inputTextField: UITextField?
alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
textField.placeholder = "Routine Name"
inputTextField = textField
})
alert.addAction(UIAlertAction(title: "Add", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
self.objects.insert(inputTextField!, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
不幸的是,这会将单元格标签设置为< _UIAlertControllerTextField:...
我猜它是在“添加”按钮的操作中我使用“inputTextField”。我不确定如何正确捕获用户提交的文本。
答案 0 :(得分:1)
当您要添加其内容时,您正在将文本字段添加到数组中。
而不是:
self.objects.insert(inputTextField!, atIndex: 0)
这样做:
self.objects.insert(inputTextField.text!, atIndex: 0)
答案 1 :(得分:0)
U可以使用[String]数组来显示TableView文本。 在alertAddAction中,U可以捕获如下文本:
var objects = [String]()
func insertNewObject(sender: AnyObject) {
var alert = UIAlertController(title: "New Routine", message: "", preferredStyle: UIAlertControllerStyle.Alert)
// var inputTextField: UITextField? // No need for this
alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
textField.placeholder = "Routine Name"
//inputTextField = textField
})
alert.addAction(UIAlertAction(title: "Add", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
if let textFields = alert.textFields{
let theTextFields = textFields as! [UITextField] // used this to capture the text
let object = theTextFields[0].text
self.objects.insert(object, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
U可以尝试看到它适用于U.