我有一个带有四个单元格的静态UItableView . 当我尝试使用insertRowsAtIndexPath tableView方法在第三个单元格后插入一行并将UIPickerView添加到添加的行时出现此错误: uncaught exception 'NSRangeException', reason: '-[__NSArrayI objectAtIndex:]: index 4 beyond bounds [0 .. 3]'
我想要实现的是iOS日历应用程序中的内联datePicker,但使用的是UIPickerView . 我想在选择/取消选择的第三行的正下方显示一个UIPicker /隐藏一个pickerView . 我也想在最后一行做同样的事情 .
NOTE: 使用pickerView添加行时,我在第四个单元格下面添加但在其他单元格之间插入单元格时不起作用 .
如果没有首先在Storyboard中创建UIPickerView,还有另一种方法可以实现这一点,我会很高兴 .
var pickerIsVisible = false
func hidePicker() {
pickerIsVisible = false
let indexPathPicker = NSIndexPath(forRow: 3, inSection: 0)
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPathPicker], withRowAnimation: .Fade)
tableView.endUpdates()
}
func showPicker() {
pickerIsVisible = true
let indexPathPicker = NSIndexPath(forRow: 3, inSection: 0)
tableView.beginUpdates()
tableView.insertRowsAtIndexPaths([indexPathPicker], withRowAnimation: .Fade)
tableView.endUpdates()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 && (indexPath.row == 3 && pickerIsVisible) {
var cell = tableView.dequeueReusableCellWithIdentifier("PickerCell") as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: "PickerCell")
cell.selectionStyle = .None
let picker = UIPickerView(frame: cell.frame)
picker.tag = 100
picker.delegate = self
picker.dataSource = self
cell.contentView.addSubview(picker)
}
return cell
} else {
return super.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 && pickerIsVisible {
return 5
} else {
return super.tableView(tableView, numberOfRowsInSection: section)
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 && indexPath.row == 2 {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
noteTextField.resignFirstResponder()
pickerIsVisible ? hidePicker() : showPicker()
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 && pickerIsVisible && indexPath.row == 3 {
return 117
} else {
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
}
override func tableView(tableView: UITableView, var indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int {
if indexPath.section == 0 && indexPath.row == 3 && pickerIsVisible {
indexPath = NSIndexPath(forRow: 0, inSection: indexPath.section)
}
return super.tableView(tableView, indentationLevelForRowAtIndexPath: indexPath)
}
1 回答
通过修改这些方法解决: