2017-05-27 232 views
0

我想動畫單元格中子視圖的addSubview。 tableview單元格具有動態高度,因此摺疊和展開的動畫是本地完成的。動畫在動態單元格高度的單元格中添加子視圖

這是代碼:

// MARK: UITableViewDelegate 

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    if let selectedCell = tableView.cellForRow(at: indexPath) as? MyCell { 
    selectedCell.showExtraView() 
    expandedCells.insert(indexPath) 
    } 
    if let prevSelectedCell = tableView.cellForRow(at: prevIndexPath) as? MyCell { 
    prevSelectedCell.hideExtraView() 
    expandedCells.remove(prevIndexPath) 
    } 
} 

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
    if expandedCells.contains(indexPath) { 
    return CGFloat(100.0) 
    } else { 
    return CGFloat(80.0) 
    } 
} 

單元代碼:

// MyCell 

func showExtraView() { 
    contentView.addSubview(extraView) 
    contentView.setNeedsLayout() 
} 

func hideExtraView() { 
    extraView.removeFromSuperview() 
    contentView.setNeedsLayout() 
} 

這是什麼樣子:

enter image description here

子視圖(extraView)包括圖像和標籤。標籤正確動畫,但圖像剛好出現在那裏,就好像它不是動畫的一部分。

回答

0

動畫您的視圖的alpha。將動畫塊中的alpha從0.0改爲1.0。

func showExtraView() { 

    extraView.alpha = 0.0 

    UIView.animate(withDuration: 0.6) { 

     contentView.addSubview(extraView)  
     extraView.alpha = 1.0 
     self.contentView.layoutIfNeeded() 

    } 
} 

func hideExtraView() { 

    UIView.animate(withDuration: 0.6, animations: { 
     extraView.alpha = 0.0 
     self.contentView.layoutIfNeeded() 
    }) { (completed) in 
     extraView.removeFromSuperview() 
    } 
}