我正在创建一个UITableViewCell
,用于在单击时展开单元格。基本上一切都有效,但是当我点击最后一个单元格时,我遇到了问题。发生这种情况时,所有单元格都会扩展到200
(高度)。以下是我的代码。我很感谢社区在这个问题上的帮助。
var selectedIndexPath : NSIndexPath?
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! Cell
cell.titleLabel.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! Cell).watchFrameChanges()
}
override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
(cell as! Cell).ignoreFrameChanges()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
for cell in tableView.visibleCells as! [Cell] {
cell.ignoreFrameChanges()
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath == selectedIndexPath {
return Cell.expandedHeight
} else {
return Cell.defaultHeight
}
}
对于tableview ell类,代码为:
var isObserving = false;
@IBOutlet weak var titleLabel: UILabel!
class var expandedHeight: CGFloat { get { return 200 } }
class var defaultHeight: CGFloat { get { return 40 } }
func checkHeight() {
titleLabel.hidden = (frame.size.height < Cell.expandedHeight)
}
func watchFrameChanges() {
if !isObserving {
addObserver(self, forKeyPath: "frame", options: [NSKeyValueObservingOptions.New, NSKeyValueObservingOptions.Initial], context: nil)
isObserving = true;
}
}
func ignoreFrameChanges() {
if isObserving {
removeObserver(self, forKeyPath: "frame")
isObserving = false;
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "frame" {
checkHeight()
}
}