2013年12月3日 星期二

iOS 開發筆記 - 解決 Storyboard UITableViewCell contentView 第一次設定 subViews frame 失效問題

為了讓自己趕快習慣 Storyboard 開發模式,瘋狂地用 Storyboard 做事 XD 除了降低原本的開發速度外,接著碰到一些好像是 bug 的奇妙問題?

這個問題是在 Storyboard 內已經拉好一個 UITableViewController ,接著在裡頭增加 UITableViewCell 後,再上頭加多個 ImageView 把玩,然而,希望 device rotation 後能後平均地顯示在 UITableViewCell 裡頭,例如有五個 ImageView 可以平均地分布。

此時在 (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 已經完成重新計算各個 ImageView 的 frame 座標。

由於 Storyboard 是以 Portrait 模式設計,因此裝置一開始從 Portrait 轉換到 Landscape 時,一切都正常顯示。但如果裝置一開始就是在 Landscape 模式時,反而那些 ImageView 卻還是依照 Storyboard 裡的 Portrait 模式設計,無論我把他們的 frame 座標更新也無用。(但經過 device rotation 後,會顯示正常)

不曉得這是不是 bug ?總之,最後就想到一招就是第一次強制 ImageView 重新歸位 XD 希望這招之後可以拿掉。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        // ...

        if( cell.tag == 0 )
        {
                cell.tag = 1;
                for (UIView *v in [cell.contentView subviews])
                {
                        [v removeFromSuperview];
                        [cell.contentView addSubview:v];
                }
        }
        return cell;
}

沒有留言:

張貼留言