我想要一个可扩展的表视图,但是当我尝试展开表格视图时,我有这个错误:
2015-10-04 19:42:25.030 SideBarMenu [7692:304078] ***由于未捕获的异常'NSRangeException'而终止应用程序,原因是:'无法删除关键路径“frame”的观察者,因为它是没有注册为观察员。'
这是完整的源代码:https://github.com/MyHappyHog/ProjectPrototype/tree/master/src/03.iOS/UI
这是源代码的一部分:
SettingViewController.swift
import UIKit
let cellID = "cell"
class SettingViewController: UITableViewController {
var selectedIndexPath : NSIndexPath?
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath)
cell.textLabel!.text = "Test Title"
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let previousIndexPath = selectedIndexPath
if indexPath == selectedIndexPath {
selectedIndexPath = nil
}
else {
selectedIndexPath = indexPath
}
var indexPaths : Array<NSIndexPath> = []
if let previous = previousIndexPath {
indexPaths += [previous]
}
if let current = selectedIndexPath {
indexPaths += [current]
}
if indexPaths.count > 0 {
tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic )
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
(cell as! SettingViewCell).watchFrameChanges()
}
override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
(cell as! SettingViewCell).ignoreFrameChanges()
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath == selectedIndexPath {
return SettingViewCell.expandedHeight
}
else {
return SettingViewCell.defaultHeight
}
}
}
SettingViewCell.swift
import UIKit
class SettingViewCell : UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var datePicker: UIDatePicker!
class var expandedHeight: CGFloat { get {return 200 } }
class var defaultHeight: CGFloat { get {return 44 } }
func checkHeight() {
datePicker.hidden = (frame.size.height < SettingViewCell.expandedHeight)
}
func watchFrameChanges() {
addObserver(self, forKeyPath: "frame", options: .New, context: nil)
checkHeight()
}
func ignoreFrameChanges() {
removeObserver(self, forKeyPath: "frame")
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "frame" {
checkHeight()
}
}
}