2015年11月4日 星期三

隱藏無內容的Self Sizing Cell

基本上看完优化UITableViewCell高度计算的那些事就可以大概瞭解從iOS7以後計算TableViewCell高度需要注意的事。

假設cell裡只有一個addressLabel,而且我們使用iOS8的self sizing,想讓無內容的cell高度變為0,也就是不顯示,可以把top跟bottom constraint的constant設為0。先把xib或storyboard中上下的constraint拉出IBOutlet到 .m 檔中,在cellForRowAtIndexPath的時候根據內容是否為空決定constant大小。

Constraint

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"ListTableViewCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
    if (cell.addressLabel.text.length == 0) {
        cell.addressLabelTopConstraint.constant = 0;
        cell.addressLabelBottomConstraint.constant = 0;
    }
    else {
        cell.addressLabelTopConstraint.constant = 15;
        cell.addressLabelBottomConstraint.constant = 15;
    }
    [cell layoutIfNeeded];
    return cell;
}

addressLabel如果沒有內容,因為Label約束與上下邊緣一致 (constant為0),所以Label高度會被自動計算為0,且不會佔任何空間。

沒有留言:

張貼留言