我製作了可擴展的tableViewCell
,當點擊時展開和摺疊,我的單元格中也有兩個標籤(dateLabel
& textLabel
),但是當我點擊單元格時,我的標籤也隨之移動。我如何使它們變爲靜態,並在點擊時阻止它們移動。當我展開我的TableViewCell時,爲什麼我的標籤會移動,並且爲什麼點擊時會獲得不同的單元格動畫?
這裏是我的類的代碼,有tableView
:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let previousIndexPath = selectedIndexPath
if indexPath == selectedIndexPath {
selectedIndexPath = nil
} else {
selectedIndexPath = indexPath
}
var indexPaths : Array<IndexPath> = []
if let previous = previousIndexPath {
indexPaths += [previous]
}
if let current = selectedIndexPath {
indexPaths += [current]
}
if indexPaths.count > 0 {
tableView.reloadRows(at: indexPaths, with: UITableViewRowAnimation.automatic)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCellID") as! CustomCell
cell.textLabel?.text=list[indexPath.row]
cell.dateLabel?.text = time.indices.contains(indexPath.row) ? time[indexPath.row] : "Not Available"
print(time.indices.contains(indexPath.row))
return (cell)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath == selectedIndexPath {
return CustomCell.expandedHeight
} else {
return CustomCell.defaultHeight
}
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
(cell as! CustomCell).watchFrameChanges()
}
override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
(cell as! CustomCell).ignoreFrameChanges()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
for cell in tableView.visibleCells as! [CustomCell] {
cell.ignoreFrameChanges()
}
}
和我CustomCell
類:
var isObserving = false;
class var expandedHeight: CGFloat { get { return 170 } }
class var defaultHeight: CGFloat { get { return 40 } }
func checkHeight() {
textView.isHidden = (frame.size.height < CustomCell.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 observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "frame" {
checkHeight()
}
}
我也得到了不同cells..like不同的動畫,我得到幻燈片第一個單元格的動畫和其餘全部淡入淡出
你能提供關於如何佈置'cell.textLabel'和'cell.dataLabel'的信息/代碼嗎?你正在使用代碼來佈局? (似乎不)或故事板與自動佈局約束? –
@PangHoMing我沒有使用任何限制..在任何標籤。 'dateLabel'在滑雪板上,但'textLabel'被編程調用。 –