我正在使用Swift 3.我有可擴展的表格視圖單元格,但是有可能根據單擊哪個單元格來獲取不同的行高度?例如,如果第一個單元格被點擊,我希望它返回420高度,如果其他單元格被點擊,我希望它返回300高度。Swift 3 - 有條件的擴展表格視圖單元格高度
這是我的細胞類。
class ResultsCell: UITableViewCell {
@IBOutlet weak var introPara : UITextView!
@IBOutlet weak var section_heading : UILabel!
class var expandedHeight : CGFloat = { get { return 420.0 } }
class var defaultHeight : CGFloat { get { return 44.0 } }
var frameAdded = false
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
section_heading.translatesAutoresizingMaskIntoConstraints = false
}
func checkHeight() {
introPara.isHidden = (frame.size.height < ResultsCell.expandedHeight)
}
func watchFrameChanges() {
if(!frameAdded) {
addObserver(self, forKeyPath: "frame", options: .new, context: nil)
checkHeight()
}
}
func ignoreFrameChanges() {
if(frameAdded){
removeObserver(self, forKeyPath: "frame")
}
}
deinit {
print("deinit called");
ignoreFrameChanges()
}
// when our frame changes, check if the frame height is appropriate and make it smaller or bigger depending
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "frame" {
checkHeight()
}
}
}
我試過的是這樣的。
var _expandedHeight : CGFloat = 420.0
class var expandedHeight : CGFloat { get { return _expandedHeight } set (newHeight) { _expandedHeight = newHeight } }
var isRow0 = false
override func awakeFromNib() {
super.awakeFromNib()
section_heading.translatesAutoresizingMaskIntoConstraints = false
if isRow0 {
ResultsCell.expandedHeight = 300.0
}
else {
ResultsCell.expandedHeight = 420.0
}
}
然後在上的getter/setter線TableViewController
...
// return the actual view for the cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let resultcell = tableView.dequeueReusableCell(withIdentifier: "resultCellTemplate", for: indexPath) as! ResultsCell
if indexPath.row == 0 {
resultcell.isRow0 = true
} else {
resultcell.isRow0 = false
}
return resultcell
}
但我發現了錯誤:instance member _expandedHeight cannot be used on type ResultsCell
我如何能實現我想要的行爲?