2015年8月21日金曜日

iOS8.xでUITableViewAutomaticDimensionを使うと、セル位置が正常にならない

iOS8.xでTableViewのセル高さの自動調整が可能です。

    self.tableView.rowHeight = UITableViewAutomaticDimension



ただし、TableViewからセル選択により画面遷移後、戻ってきたときなど再表示をするとセル位置が調整されていないことがあります。 対策として、一度表示したセルの高さを保持しておいて、estimatedHeightForRowAtIndexPathで値を返します。

    var cellHeight:Dictionary = ["":0]
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        cell.contentView.updateConstraints()
        self.cellHeight[String(indexPath.item )] = Float(cell.frame.size.height)
        
    }
    
    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if(self.cellHeight[String(indexPath.item )] != nil){
            return CGFloat(self.cellHeight[String(indexPath.item )]!)
        }
        return self.tableView.estimatedRowHeight
        
    }