Cómo detectar iPhone 5 (dispositivos de pantalla ancha)?
Acabo de actualizar a XCode 4.5 GM y descubrí que ahora puede aplicar el tamaño '4" Retina' a su controlador de vista en el guion gráfico.
Ahora, si quiero crear una aplicación que se ejecute en ambos iPhone 4 y 5, por supuesto que tengo que construir cada ventana dos veces, pero también tengo que detectar si el usuario tiene un iPhone con pantalla de 3.5" o 4" y luego aplicar la vista.
¿Cómo debo hacer eso?
24 answers
En primer lugar, no debe reconstruir todas sus vistas para adaptarse a una nueva pantalla, ni usar diferentes vistas para diferentes tamaños de pantalla.
Utilice las capacidades de redimensionamiento automático de iOS, para que sus vistas puedan ajustar y adaptar cualquier tamaño de pantalla.
Eso no es muy difícil, lee alguna documentación sobre eso. Te ahorrará mucho tiempo.
IOS 6 también ofrece nuevas características sobre esto, pero esto todavía está bajo NDA en este momento.
Asegúrese de leer el API changelog en el sitio web del desarrollador de Apple, si puede acceder a él.
Editar : Como iOS 6 está ahora fuera, compruebe el nuevo Diseño automático capacidades.
Dicho esto, si realmente necesita detectar el iPhone 5, simplemente puede confiar en el tamaño de pantalla .
[ [ UIScreen mainScreen ] bounds ].size.height
La pantalla del iPhone 5 tiene una altura de 568.
Puedes imaginar una macro, para simplificar todo esto:
#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
El uso de fabs
con el epsilon está aquí para evite errores de precisión, al comparar puntos flotantes, como se señala en los comentarios de H2CO3.
Así que a partir de ahora puedes usarlo en sentencias estándar if/else:
if( IS_IPHONE_5 )
{}
else
{}
Editar - Mejor detección
Como afirman algunas personas, esto solo detecta una pantalla panorámica, no un iPhone 5 real.
Las próximas versiones del iPod touch tal vez también tengan una pantalla de este tipo, por lo que podemos usar otro conjunto de macros.
Vamos a cambiar el nombre del original macro IS_WIDESCREEN
:
#define IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
Y vamos a añadir macros de detección de modelo:
#define IS_IPHONE ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPhone" ] )
#define IS_IPOD ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPod touch" ] )
De esta manera, podemos asegurarnos de tener un modelo de iPhone Y una pantalla panorámica, y podemos redefinir la macro IS_IPHONE_5
:
#define IS_IPHONE_5 ( IS_IPHONE && IS_WIDESCREEN )
También tenga en cuenta que, como indica @LearnCocos2D, estas macros no funcionarán si la aplicación no está optimizada para la pantalla del iPhone 5 (falta la [email protected] imagen), ya que el tamaño de la pantalla seguirá siendo de 320x480 en tal caso.
No creo que esto pueda ser un problema, ya que no veo por qué querríamos detectar un iPhone 5 en una aplicación no optimizada.
IMPORTANTE: compatibilidad con iOS 8
En iOS 8, la propiedad bounds
de la clase UIScreen
ahora refleja la orientación del dispositivo .
Así que obviamente, el código anterior no funcionará fuera de la caja.
Para arreglar esto, simplemente puede usar la nueva propiedad nativeBounds
, en lugar de bounds
, ya que no cambiará con la orientación, y ya que está basada en un retrato hacia arriba modo.
Tenga en cuenta que las dimensiones de nativeBounds
se mide en píxeles, por lo que para un iPhone 5 la altura será1136 en lugar de 568.
Si también estás apuntando a iOS 7 o inferior, asegúrate de usar detección de funciones, ya que llamar a nativeBounds
antes de iOS 8 bloqueará tu aplicación:
if( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] )
{
/* Detect using nativeBounds - iOS 8 and greater */
}
else
{
/* Detect using bounds - iOS 7 and lower */
}
Puede adaptar las macros anteriores de la siguiente manera:
#define IS_WIDESCREEN_IOS7 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
#define IS_WIDESCREEN_IOS8 ( fabs( ( double )[ [ UIScreen mainScreen ] nativeBounds ].size.height - ( double )1136 ) < DBL_EPSILON )
#define IS_WIDESCREEN ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_WIDESCREEN_IOS8 : IS_WIDESCREEN_IOS7 )
Y obviamente, si necesita detectar un iPhone 6 o 6 Plus, use los tamaños de pantalla correspondientes.
Final nota
Comentarios y sugerencias han sido incorporados en este post.
Gracias a todos.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-19 02:46:28
Probado y diseñado para cualquier combinación de SDK y OS:
Swift
Se han añadido tipos de iPad. iPad 2 y iPad mini son iPads no retina. Mientras que el iPad Mini 2 y superior, el iPad 3, 4, iPad Air, Air 2, Air 3 y iPad Pro 9.7 tienen la misma resolución lógica de 1024. El iPad Pro tiene una longitud máxima de 1366. Referencia
import UIKit
public enum DisplayType {
case unknown
case iphone4
case iphone5
case iphone6
case iphone6plus
case iPadNonRetina
case iPad
case iPadProBig
static let iphone7 = iphone6
static let iphone7plus = iphone6plus
}
public final class Display {
class var width:CGFloat { return UIScreen.main.bounds.size.width }
class var height:CGFloat { return UIScreen.main.bounds.size.height }
class var maxLength:CGFloat { return max(width, height) }
class var minLength:CGFloat { return min(width, height) }
class var zoomed:Bool { return UIScreen.main.nativeScale >= UIScreen.main.scale }
class var retina:Bool { return UIScreen.main.scale >= 2.0 }
class var phone:Bool { return UIDevice.current.userInterfaceIdiom == .phone }
class var pad:Bool { return UIDevice.current.userInterfaceIdiom == .pad }
class var carplay:Bool { return UIDevice.current.userInterfaceIdiom == .carPlay }
class var tv:Bool { return UIDevice.current.userInterfaceIdiom == .tv }
class var typeIsLike:DisplayType {
if phone && maxLength < 568 {
return .iphone4
}
else if phone && maxLength == 568 {
return .iphone5
}
else if phone && maxLength == 667 {
return .iphone6
}
else if phone && maxLength == 736 {
return .iphone6plus
}
else if pad && !retina {
return .iPadNonRetina
}
else if pad && retina && maxLength == 1024 {
return .iPad
}
else if pad && maxLength == 1366 {
return .iPadProBig
}
return .unknown
}
}
Véalo en acción https://gist.github.com/hfossli/bc93d924649de881ee2882457f14e346
Nota: Si, por ejemplo, iPhone 6 está en modo de zoom UI es una versión ampliada del iPhone 5. Estas funciones no es determinar el tipo de dispositivo, pero el modo de visualización por lo tanto iPhone 5 es el resultado deseado en este ejemplo.
Objetivo-C
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_RETINA ([[UIScreen mainScreen] scale] >= 2.0)
#define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)
#define SCREEN_MAX_LENGTH (MAX(SCREEN_WIDTH, SCREEN_HEIGHT))
#define SCREEN_MIN_LENGTH (MIN(SCREEN_WIDTH, SCREEN_HEIGHT))
#define IS_ZOOMED (IS_IPHONE && SCREEN_MAX_LENGTH == 736.0)
#define IS_IPHONE_4_OR_LESS (IS_IPHONE && SCREEN_MAX_LENGTH < 568.0)
#define IS_IPHONE_5 (IS_IPHONE && SCREEN_MAX_LENGTH == 568.0)
#define IS_IPHONE_6 (IS_IPHONE && SCREEN_MAX_LENGTH == 667.0)
#define IS_IPHONE_6P (IS_IPHONE && SCREEN_MAX_LENGTH == 736.0)
Uso: http://pastie.org/9687735
Nota: Si, por ejemplo, el iPhone 6 está en modo zoom, la interfaz de usuario es una versión ampliada del iPhone 5. Estas funciones no es determinar el tipo de dispositivo, pero el modo de visualización por lo tanto iPhone 5 es el resultado deseado en este ejemplo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-04 20:34:09
Solución realmente simple
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
CGSize result = [[UIScreen mainScreen] bounds].size;
if(result.height == 480)
{
// iPhone Classic
}
if(result.height == 568)
{
// iPhone 5
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-25 17:35:55
Ahora necesitamos tener en cuenta los tamaños de pantalla del iPhone 6 y 6Plus. He aquí una respuesta actualizada
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
//its iPhone. Find out which one?
CGSize result = [[UIScreen mainScreen] bounds].size;
if(result.height == 480)
{
// iPhone Classic
}
else if(result.height == 568)
{
// iPhone 5
}
else if(result.height == 667)
{
// iPhone 6
}
else if(result.height == 736)
{
// iPhone 6 Plus
}
}
else
{
//its iPad
}
Alguna información útil
iPhone 6 Plus 736x414 points 2208x1242 pixels 3x scale 1920x1080 physical pixels 401 physical ppi 5.5"
iPhone 6 667x375 points 1334x750 pixels 2x scale 1334x750 physical pixels 326 physical ppi 4.7"
iPhone 5 568x320 points 1136x640 pixels 2x scale 1136x640 physical pixels 326 physical ppi 4.0"
iPhone 4 480x320 points 960x640 pixels 2x scale 960x640 physical pixels 326 physical ppi 3.5"
iPhone 3GS 480x320 points 480x320 pixels 1x scale 480x320 physical pixels 163 physical ppi 3.5"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-24 13:07:12
Me he tomado la libertad de poner la macro de Macmade en una función C, y nombrarla correctamente porque detecta disponibilidad de pantalla ancha y NO necesariamente el iPhone 5.
La macro tampoco detecta la ejecución en un iPhone 5 en caso de que el proyecto no incluya el [email protected] . Sin la nueva imagen Predeterminada, el iPhone 5 reportará un tamaño de pantalla normal de 480x320 (en puntos). Así que la comprobación no es solo para la disponibilidad de pantalla ancha, sino para el modo de pantalla ancha está habilitado también.
BOOL isWidescreenEnabled()
{
return (BOOL)(fabs((double)[UIScreen mainScreen].bounds.size.height -
(double)568) < DBL_EPSILON);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-21 14:44:38
Aquí están nuestros códigos, prueba pasada en ios7 / ios8 para iphone4, iphone5, ipad, iphone6, iphone6p, no importa en dispositivos o simulador:
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) // iPhone and iPod touch style UI
#define IS_IPHONE_5_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 568.0f)
#define IS_IPHONE_6_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 667.0f)
#define IS_IPHONE_6P_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 736.0f)
#define IS_IPHONE_4_AND_OLDER_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height < 568.0f)
#define IS_IPHONE_5_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 568.0f)
#define IS_IPHONE_6_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 667.0f)
#define IS_IPHONE_6P_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 736.0f)
#define IS_IPHONE_4_AND_OLDER_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) < 568.0f)
#define IS_IPHONE_5 ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_5_IOS8 : IS_IPHONE_5_IOS7 )
#define IS_IPHONE_6 ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_6_IOS8 : IS_IPHONE_6_IOS7 )
#define IS_IPHONE_6P ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_6P_IOS8 : IS_IPHONE_6P_IOS7 )
#define IS_IPHONE_4_AND_OLDER ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_4_AND_OLDER_IOS8 : IS_IPHONE_4_AND_OLDER_IOS7 )
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-07 07:25:45
Usé la respuesta de hfossli y la traduje a Swift
let IS_IPAD = UIDevice.currentDevice().userInterfaceIdiom == .Pad
let IS_IPHONE = UIDevice.currentDevice().userInterfaceIdiom == .Phone
let IS_RETINA = UIScreen.mainScreen().scale >= 2.0
let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width
let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height
let SCREEN_MAX_LENGTH = max(SCREEN_WIDTH, SCREEN_HEIGHT)
let SCREEN_MIN_LENGTH = min(SCREEN_WIDTH, SCREEN_HEIGHT)
let IS_IPHONE_4_OR_LESS = (IS_IPHONE && SCREEN_MAX_LENGTH < 568.0)
let IS_IPHONE_5 = (IS_IPHONE && SCREEN_MAX_LENGTH == 568.0)
let IS_IPHONE_6 = (IS_IPHONE && SCREEN_MAX_LENGTH == 667.0)
let IS_IPHONE_6P = (IS_IPHONE && SCREEN_MAX_LENGTH == 736.0)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-05 21:20:14
Esta es la macro para mi proyecto cocos2d. debería ser lo mismo para otras aplicaciones.
#define WIDTH_IPAD 1024
#define WIDTH_IPHONE_5 568
#define WIDTH_IPHONE_4 480
#define HEIGHT_IPAD 768
#define HEIGHT_IPHONE 320
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
//width is height!
#define IS_IPHONE_5 ( [ [ UIScreen mainScreen ] bounds ].size.height == WIDTH_IPHONE_5 )
#define IS_IPHONE_4 ( [ [ UIScreen mainScreen ] bounds ].size.height == WIDTH_IPHONE_4 )
#define cp_ph4(__X__, __Y__) ccp(cx_ph4(__X__), cy_ph4(__Y__))
#define cx_ph4(__X__) (IS_IPAD ? (__X__ * WIDTH_IPAD / WIDTH_IPHONE_4) : (IS_IPHONE_5 ? (__X__ * WIDTH_IPHONE_5 / WIDTH_IPHONE_4) : (__X__)))
#define cy_ph4(__Y__) (IS_IPAD ? (__Y__ * HEIGHT_IPAD / HEIGHT_IPHONE) : (__Y__))
#define cp_pad(__X__, __Y__) ccp(cx_pad(__X__), cy_pad(__Y__))
#define cx_pad(__X__) (IS_IPAD ? (__X__) : (IS_IPHONE_5 ? (__X__ * WIDTH_IPHONE_5 / WIDTH_IPAD) : (__X__ * WIDTH_IPHONE_4 / WIDTH_IPAD)))
#define cy_pad(__Y__) (IS_IPAD ? (__Y__) : (__Y__ * HEIGHT_IPHONE / HEIGHT_IPAD))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-29 04:32:27
if ((int)[[UIScreen mainScreen] bounds].size.height == 568)
{
// This is iPhone 5 screen
} else {
// This is iPhone 4 screen
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-12 12:03:22
En Swift, iOS 8 + project me gusta hacer una extensión en UIScreen
, como:
extension UIScreen {
var isPhone4: Bool {
return self.nativeBounds.size.height == 960;
}
var isPhone5: Bool {
return self.nativeBounds.size.height == 1136;
}
var isPhone6: Bool {
return self.nativeBounds.size.height == 1334;
}
var isPhone6Plus: Bool {
return self.nativeBounds.size.height == 2208;
}
}
(NOTA: nativeBounds
está en píxeles).
Y entonces el código será como:
if UIScreen.mainScreen().isPhone4 {
// do smth on the smallest screen
}
Así que el código deja claro que esto es una comprobación para la pantalla principal, no para el modelo de dispositivo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-22 15:37:56
Tomando prestado de la respuesta de Samrat Mazumdar, aquí hay un método corto que estima el tamaño de la pantalla del dispositivo. Funciona con los últimos dispositivos, pero puede fallar en los futuros (como todos los métodos de adivinar podrían). También se confundirá si el dispositivo está siendo reflejado (devuelve el tamaño de pantalla del dispositivo, no el tamaño de pantalla reflejado)
#define SCREEN_SIZE_IPHONE_CLASSIC 3.5
#define SCREEN_SIZE_IPHONE_TALL 4.0
#define SCREEN_SIZE_IPAD_CLASSIC 9.7
+ (CGFloat)screenPhysicalSize
{
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
CGSize result = [[UIScreen mainScreen] bounds].size;
if (result.height < 500)
return SCREEN_SIZE_IPHONE_CLASSIC; // iPhone 4S / 4th Gen iPod Touch or earlier
else
return SCREEN_SIZE_IPHONE_TALL; // iPhone 5
}
else
{
return SCREEN_SIZE_IPAD_CLASSIC; // iPad
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-10 23:25:50
Creo que debería ser bueno si esta macro funcionará en dispositivo y simulador, a continuación se muestra la solución.
#define IS_WIDESCREEN (fabs((double)[[UIScreen mainScreen]bounds].size.height - (double)568) < DBL_EPSILON)
#define IS_IPHONE (([[[UIDevice currentDevice] model] isEqualToString:@"iPhone"]) || ([[[UIDevice currentDevice] model] isEqualToString: @"iPhone Simulator"]))
#define IS_IPOD ([[[UIDevice currentDevice]model] isEqualToString:@"iPod touch"])
#define IS_IPHONE_5 ((IS_IPHONE || IS_IPOD) && IS_WIDESCREEN)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-08 10:38:10
Encontré que las respuestas no incluyen un caso especial para Simuladores.
#define IS_WIDESCREEN ( [ [ UIScreen mainScreen ] bounds ].size.height == 568 )
#define IS_IPHONE ([[ [ UIDevice currentDevice ] model ] rangeOfString:@"iPhone"].location != NSNotFound)
#define IS_IPAD ([[ [ UIDevice currentDevice ] model ] rangeOfString:@"iPad"].location != NSNotFound)
#define IS_IPHONE_5 ( IS_IPHONE && IS_WIDESCREEN )
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-07 21:39:48
+(BOOL)isDeviceiPhone5
{
BOOL iPhone5 = FALSE;
CGRect screenBounds = [[UIScreen mainScreen] bounds];
if (screenBounds.size.height == 568)
{
// code for 4-inch screen
iPhone5 = TRUE;
}
else
{
iPhone5 = FALSE;
// code for 3.5-inch screen
}
return iPhone5;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-19 14:41:52
CGFloat height = [UIScreen mainScreen].bounds.size.height;
NSLog(@"screen soze is %f",height);
if (height>550) {
// 4" screen-do some thing
}
else if (height<500) {
// 3.5 " screen- do some thing
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-11 05:39:06
Confiar en el tamaño es incorrecto en muchos niveles. ¿Le preguntamos al sistema?
- (NSString *) getDeviceModel
{
struct utsname systemInfo;
uname(&systemInfo);
return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
}
Tomado de ¿La mejor manera de detectar el tipo de hardware, iPhone4 o iPhone5?, respuesta de edzio27.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:06
De esta manera puede detectar la familia de dispositivos.
#import <sys/utsname.h>
NSString* deviceName()
{
struct utsname systemInformation;
uname(&systemInformation);
NSString *result = [NSString stringWithCString:systemInformation.machine
encoding:NSUTF8StringEncoding];
return result;
}
#define isIPhone5 [deviceName() rangeOfString:@"iPhone5,"].location != NSNotFound
#define isIPhone5S [deviceName() rangeOfString:@"iPhone6,"].location != NSNotFound
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-10 07:17:54
Si el proyecto se crea con Xcode 6, utilice el código mencionado a continuación para detectar los dispositivos..
printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] nativeBounds].size.width,(int)[[UIScreen mainScreen] nativeBounds].size.height);
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
{
if([[UIScreen mainScreen] nativeBounds].size.height == 960 || [[UIScreen mainScreen] nativeBounds].size.height == 480){
printf("Device Type : iPhone 4,4s ");
}else if([[UIScreen mainScreen] nativeBounds].size.height == 1136){
printf("Device Type : iPhone 5,5S/iPod 5 ");
}else if([[UIScreen mainScreen] nativeBounds].size.height == 1334){
printf("Device Type : iPhone 6 ");
}else if([[UIScreen mainScreen] nativeBounds].size.height == 2208){
printf("Device Type : iPhone 6+ ");
}
}
}else{
printf("Device Type : iPad");
}
Si el proyecto se creó en Xcode 5 y se abrió en Xcode 6, utilice el código mencionado a continuación para detectar los dispositivos.(Este código funciona si no se asignan imágenes de lanzamiento para iPhone 6,6+)
printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] nativeBounds].size.width,(int)[[UIScreen mainScreen] nativeBounds].size.height);
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
{
if([[UIScreen mainScreen] nativeBounds].size.height == 960 || [[UIScreen mainScreen] nativeBounds].size.height == 480){
printf("Device Type : iPhone 4,4s");
appType=1;
}else if([[UIScreen mainScreen] nativeBounds].size.height == 1136 || [[UIScreen mainScreen] nativeBounds].size.height == 1704){
printf("Device Type : iPhone 5,5S,6,6S/iPod 5 ");
appType=3;
}
}
}else{
printf("Device Type : iPad");
appType=2;
}
Si todavía está usando Xcode 5 todos juntos, use el siguiente código para detectar los dispositivos (iPhone 6 y 6+ no serán detected)
printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] bounds].size.width,(int)[[UIScreen mainScreen] bounds].size.height);
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
{
CGSize result = [[UIScreen mainScreen] bounds].size;
CGFloat scale = [UIScreen mainScreen].scale;
result = CGSizeMake(result.width * scale, result.height * scale);
if(result.height == 960 || result.height == 480){
printf("Device Type : iPhone 4,4S ");
}else if(result.height == 1136){
printf("Device Type : iPhone 5s/iPod 5");
}
}
}else{
printf("Device Type : iPad");
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-28 17:24:27
Añadir un nuevo archivo Swift'->
AppDelegateEx.swift
-
Añadir una extensión a
AppDelegate
import UIKit extension AppDelegate { class func isIPhone5 () -> Bool{ return max(UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height) == 568.0 } class func isIPhone6 () -> Bool { return max(UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height) == 667.0 } class func isIPhone6Plus () -> Bool { return max(UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height) == 736.0 } }
-
Uso:
if AppDelegate.isIPhone5() { collectionViewTopConstraint.constant = 2 }else if AppDelegate.isIPhone6() { collectionViewTopConstraint.constant = 20 }
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-27 02:13:47
Esto ha sido respondido cien veces pero esta solución funcionó mejor para mí. Es una función auxiliar simple y no requiere extender una clase de sistema.
Swift 3 Helper:
func phoneSizeInInches(defaultValue: Float = 4.7) -> Float {
switch (UIScreen.main.nativeBounds.size.height) {
case 960, 480:
return 3.5
case 1136:
return 4
case 1334:
return 4.7
case 2208:
return 5.5
default:
return defaultValue
}
}
Esto se debe a que es fácil memorizar los tamaños de pulgadas de un teléfono, como el dispositivo de "5.5 pulgadas" o "4.7 pulgadas", pero es difícil recordar los tamaños exactos de píxeles.
if phoneSizeInInches() == 4 {
//do something with only 4 inch iPhones
}
Esto también te da la oportunidad de hacer algo como esto:
if phoneSizeInInches() < 5.5 {
//do something all iPhones smaller than the plus
}
El "Valor predeterminado" asegura que su código siempre optará por un tamaño seguro si Apple lanza un nuevo tamaño de dispositivo y aún no has actualizado tu aplicación.
if phoneSizeInInches(defaultValue: 4.7) == 4 {
//if a new iPhone size is introduced, your code will default to behaving like a 4.7 inch iPhone
}
Tenga en cuenta que esto es específico para aplicaciones de teléfono, necesitará algunos cambios para los universales.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-03 03:06:39
En Swift 3 puedes usar mi clase simple KRDeviceType.
Https://github.com/ulian-onua/KRDeviceType
Está bien documentado y soporta operadores ==, >=,
Por ejemplo, para detectar si el dispositivo tiene límites de iPhone 6 / 6s / 7, solo puede usar la siguiente comparación:
if KRDeviceType() == .iPhone6 {
// Perform appropiate operations
}
Para detectar si el dispositivo tiene límites de iPhone 5/5S/SE o anterior (iPhone 4s) puede usar la siguiente comparación:
if KRDeviceType() <= .iPhone5 { //iPhone 5/5s/SE of iPhone 4s
// Perform appropiate operations (for example, set up constraints for those old devices)
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-09 09:48:21
Utilice el siguiente código:
CGFloat screenScale = [[UIScreen mainScreen] scale];
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale);
if (screenSize.height==1136.000000)
{
// Here iPhone 5 View
// Eg: Nextview~iPhone5.Xib
} else {
// Previous Phones
// Eg : Nextview.xib
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-29 12:07:46
Aquí está la prueba correcta del dispositivo, sin depender de la orientación
- (BOOL)isIPhone5
{
CGSize size = [[UIScreen mainScreen] bounds].size;
if (MIN(size.width,size.height) == 320 && MAX(size.width,size.height == 568)) {
return YES;
}
return NO;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-13 12:58:25
Se utiliza para detectar dispositivos iPhone y iPad de todos los versons.
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPHONE_5 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 568.0)
#define IS_IPHONE_6 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 667.0)
#define IS_IPHONE_6_PLUS (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 736.0)
#define IS_RETINA ([[UIScreen mainScreen] scale] == 2.0)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-31 14:04:20