[英]Recalculating subview sizes on rotation in iOS 7
我有一個方法,我調用來計算我在自定義UITableViewCell
子類中的一堆標簽的大小,該子類位於UIPopoverController
。 當用戶旋轉設備時,我需要重新計算尺寸,然后重新繪制表格以使用新尺寸。 我嘗試檢測旋轉的每個方法都是折舊的,不會被調用,或者在正確的時間沒有被調用。 是否有一種方法會在旋轉設備時自動調用,我可以重新計算我的尺寸?
編輯:我嘗試了什么,為什么它不起作用:
shouldAutorotate
- 沒有被召喚 - 顯然是貶值的。 layoutSubviews
- 被調用,但如果我在這里嘗試[self.tableView reloadData]
,我會陷入無限循環 UIDeviceOrientationDidChangeNotification
NSNotificationCenter
觀察者 - 在我的控制器知道它的新尺寸之前調用,所以我不能在這里重新計算我的尺寸 layoutSubviews
[self.tableView setNeedsDisplay]
- 不會提示重新繪制表格。 didRotateFromInterfaceOrientation
- 沒有被調用 - 顯然是折舊的。 編輯2:關於我正在嘗試做的更多細節
我正在嘗試模仿“行 - 列”樣式表,並排列標簽以模仿列。 當我重新計算大小時,我遍歷表的所有行,然后遍歷該行中的每個“列”。 我得到每列的寬度,並跟蹤每列的所有行中的最大寬度。 然后我操縱寬度和字體大小之間的間距來獲得它,這樣如果任何行在每列中都有最寬的標簽,它仍然適合屏幕。
您不希望依賴單元格內部的實際渲染UILabel來計算“列”寬度。 改為:
calculateColumnWidthsForInterfaceOrientation:
的方法calculateColumnWidthsForInterfaceOrientation:
它接受一個UIInterfaceOrientation
。 在該方法中,使用UIInterfaceOrientationIsLandscape(orientation)
檢查請求的方向是縱向還是橫向。 然后,根據方向,瀏覽要在標簽中顯示的數據,並使用NSString的sizeWithAttributes:
方法(或其衍生產品之一)查找最寬的列寬。 將這些值緩存在數組或其他內容中。 setColumnWidths:
等方法添加到自定義表格視圖單元格中,該單元格采用所需的列寬。 tableView:cellForRowAtIndexPath:
方法中,檢索緩存的列寬並使用setColumnWidths:
方法在單元格上設置它。 didRotateFromInterfaceOrientation:
. 在其中,調用calculateColumnWidthsForInterfaceOrientation:
使用給定的方向,然后調用[self.tableView reloadData]
。 viewDidLoad
,調用[self calculateColumnWidthsForInterfaceOrientation:self.interfaceOrientation]
在第一次旋轉之前進行數據的初始設置。 這應該夠了吧。
更新: 單元格的總寬度應等於表格視圖的總寬度。 這可以通過自動布局或其他方式進行管理。 該大小將反映在單元格的幀大小中。
更新2:由於我們正在談論一個彈出窗口 ,你可以簡單地在willRotateToInterfaceOrientation:duration:
中willRotateToInterfaceOrientation:duration:
,然后在didRotateFromInterfaceOrientation:
完成輪換后再次使用新的所需尺寸顯示它didRotateFromInterfaceOrientation:
。
在layoutSubviews中嘗試重新計算子視圖一個單元格
例如在CustomCell.m中
- (void)layoutSubviews
{
UIViewController *viewController = (id)[(AppDelegate *)[UIApplication sharedApplication].delegate window].rootViewController;
if (UIInterfaceOrientationIsPortrait(viewController.interfaceOrientation))
self.backgroundColor = [UIColor redColor];
else
self.backgroundColor = [UIColor greenColor];
}
您是否考慮過使用自動布局來定義tableView和單元格? 使用適當的約束與updateConstraints
一起在設備旋轉時更新單元updateConstraints
局應該有所幫助。 使用此方法,您可以設置每個“列”標簽的preferredMaxLayoutWidth
,並定義約束以處理適當的水平填充,無論其方向如何。
此外,如果使用iOS 7,那么您應該實現popoverController:willRepositionPopoverToRect:inView:
在旋轉時處理子視圖的布局,除非您從條形按鈕項目顯示彈出窗口。 我建議您查看UIPopoverController類參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.