我有一个拆分视图控制器(主 – 细节).我正在为iPhone 6 Plus优化它.
这是问题所在.选择单元格时,它会执行show-detail segue并在详细视图中显示单元格信息.但是,删除单元格时,即使单元格不再存在,详细视图也会保留单元格信息.
这是一个例子:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
//code that deletes my cell/not needed for example
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
let splitController = self.splitViewController!.viewControllers
self.detailViewController = splitController.last? as? detailedController
if let detail = detailViewController {
detail.title = "Select an item"
//detail.title is a variable in the view controller
//on the views "viewDidLoad" it sets a label.text as title.
}
}
}
我想执行操作:detail.title =“选择一个项目”,以便视图不再显示已删除的单元格.我尝试通过代码创建一个新的segue.没运气.
想法?
最佳答案 请执行下列操作:
>确保设置详细视图控制器的segue具有标识符.在示例Master-Detail项目中,标识符为“showDetail”.您可以通过在项目的“文档大纲视图”中选择segue来查找标识符,然后在“属性”检查器中查找segue的“标识符”字段.
>删除行时以编程方式调用此segue:
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Call showDetail when in a splitViewController and 2 view controllers
// are present
if self.splitViewController?.viewControllers.count == 2 {
self.performSegueWithIdentifier("showDetail", sender: self)
}
...
>在prepareForSegue中,确保选中所选行.当您从单元格删除代码中调用segue时,将不会选择任何行,并且indexPathForSelectedRow()将返回nil:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
// set up destination view controller in the normal way
...
} else {
// No row was selected which means either this is the initial setup
// or we came here from the row delete code
let splitController = self.splitViewController!.viewControllers
self.detailViewController = splitController.last? as? detailedController
if let detail = detailViewController {
detail.title = "Select an item"
...
}
}
}
注意:如果详细视图控制器在未设置detail.title时具有默认状态,并且此默认状态是您希望目标视图控制器在未选择任何行时的样子,那么您甚至不需要prepareForSegue中的else子句.这是Master-Detail iOS应用程序的示例.只需要从编辑代码中以编程方式调用segue,这一切都可以正常工作.