2012-04-26 30 views
5

Tôi cần lấy hướng thiết bị từ ViewController. Tôi không thể căn cứ vào:Cách nhận hướng thiết bị qua tham chiếu UIView?

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; 

vì đôi khi nó trả về định hướng không rõ (ví dụ như khi thiết bị đặt trên bàn).

Tôi chỉ cần biết theo định hướng nào là UIView hiện tại của tôi được hiển thị (có phải là phong cảnh bên trái hoặc phong cảnh bên phải). Tôi không cần phải có giá trị này cập nhật khi định hướng thay đổi, tôi chỉ muốn biết nó, khi tôi yêu cầu nó. Chỉ cần một số tham chiếu chế độ xem.orientation;). Có cái gì đó sẽ giúp tôi? Tôi đã đọc tài liệu UIView, tìm thấy một số tài liệu tham khảo để UIWindow, nhưng không có gì có thể giúp tôi.

Trả lời

13

Bạn cũng có thể nhận được hướng thiết bị từ UIApplication, có bạn đã cố gắng sử dụng

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; 
+1

Đó là chính xác những gì tôi đã lo oking cho. Bây giờ tôi có thể nhận được các thành phần UIKit định hướng và sử dụng nó. Cảm ơn rất nhiều! – thelion

-1

Sau đây là các mẫu mã để làm như vậy. Có một biến có tên là deviceOrientation và nó sẽ trả lời hướng hiện tại của thiết bị, bất cứ khi nào được hỏi.

UIDeviceOrientation deviceOrientation; 

- (void)viewWillAppear:(BOOL)animated 
{ 
    deviceOrientation = (UIDeviceOrientation)[[UIApplication sharedApplication] statusBarOrientation]; 
    [self willAnimateRotationToInterfaceOrientation:deviceOrientation duration:0.5]; 
} 

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration 
{ 
    deviceOrientation = (UIDeviceOrientation)interfaceOrientation; 
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) 
    { 
     NSLog(@"Landscape"); 
    } 
    else 
    { 
     NSLog(@"Portrait"); 
    } 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return TRUE; 
} 
4

UIViewController có một tài sản

UIInterfaceOrientation interfaceOrientation; 

Vì vậy, trong UIViewController, bạn có thể truy cập vào các định hướng hiện tại của thiết bị bất cứ lúc nào thông qua

UIInterfaceOrientation myCurrentOrientation = self.interfaceOrientation; 
+0

Không được chấp nhận từ iOS 8.0 –

0

Swift Version

let currentOrientation:UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation 


    if currentOrientation.isPortrait { 

     print("PORTRAIT") 

    } else if currentOrientation.isLandscape { 

     print("LANDSCAPE") 

    } 
Các vấn đề liên quan