我想使用UIDeviceOrientationDidChangeNotification
旋轉我的「containerView」UIView(屏幕截圖中的半透明紅框),然後稍後(旋轉後)將子圖層添加到視圖的圖層,但我發現只有containerView.layer的邊界被調整大小,而不是containerView.layer的框架! :(旋轉UIView,包括CALayer界限和CALayer框架
下面是它的外觀在肖像:
示例代碼:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)viewDidAppear:(BOOL)animated
{
CALayer *r = [CALayer layer];
r.frame = CGRectMake(0, 0, 100, 100);
r.contents = (id)[[UIImage imageNamed:@"r.png"] CGImage];
[self.containerView.layer addSublayer:r];
}
- (void)deviceRotated:(NSNotification *)notification
{
...
if (orientation == UIDeviceOrientationLandscapeLeft) {
self.containerView.transform = CGAffineTransformMakeRotation(RADIANS(90));
self.containerView.bounds = CGRectMake(0, 0, 411.0, 320.0);
NSLog(@"container bounds: %@", NSStringFromCGRect(self.containerView.bounds));
NSLog(@"container layer frame: %@", NSStringFromCGRect(self.containerView.layer.frame));
NSLog(@"container layer bounds: %@", NSStringFromCGRect(self.containerView.layer.bounds));
CALayer *testLayer = [CALayer layer];
testLayer.backgroundColor = [[UIColor blueColor] CGColor];
testLayer.bounds = self.containerView.layer.frame;
testLayer.position = CGPointMake(CGRectGetMidX(testLayer.bounds), CGRectGetMidY(testLayer.bounds));
[self.containerView.layer addSublayer:testLayer];
}
}
其中,旋轉後,打印:
container bounds: {{0, 0}, {411, 320}}
container layer frame: {{0, 0}, {320, 411}}
container layer bounds: {{0, 0}, {411, 320}}
(注意層的幀依然320寬,411高。)
所以現在它看起來像:
我也試圖改變邊界前設置的中心,但看起來像:
我知道containerView的層沒有按't自動調整大小,所以我試着在變換後設置圖層的邊框... self.containerView.layer.frame = self.containerView.bounds;
然後打印出來:
container bounds: {{0, 0}, {320, 411}}
container layer frame: {{0, 0}, {411, 320}}
container layer bounds: {{0, 0}, {320, 411}}
,看起來像:
哎呀!
對於所有視圖autoResizesSubviews設置爲YES,clipsToBounds設置爲NO。我無法使用shouldAutorotateToInterfaceOrientation
,因爲真正的應用程序將具有相機預覽,所以我希望根視圖保持縱向。
我必須缺少一些東西,我如何在containerView上進行轉換以使其圖層的邊界和框架相同,但我無法弄清楚它是什麼!任何幫助將非常感激。
更新 - 修正:
設置新添加圖層邊界(testLayer.bounds
)到contentView.layer.bounds
代替contentView.layer.frame
的伎倆。 (因爲轉換contentView會使其layer.frame失效。)謝謝Michael!
修正:
在我作爲anwser發佈之前,您是否嘗試過在self.containerView.bounds = CGRectMake(0,0,411.0,320。0); – Kaiser
感謝您的建議!我試過了,它看起來幾乎就在那裏:http://f.cl.ly/items/371I0q1O3O0e0E3A0O0P/r_land_bounds_320_411.png - 儘管容器層框架是{{-45.5,45.5},{411,320}和圖層的邊界是:{{0,0},{320,411}} – taber
當視圖已被轉換時,幀值無用。從apple doc警告:如果transform屬性不是標識轉換,則此(frame)屬性的值是未定義的,因此應該忽略。 – Kaiser