LoginSignup
13
13

More than 5 years have passed since last update.

iOS7でもUITraitCollectionを使いたい

Last updated at Posted at 2014-06-26

UITraitCollection Reference
https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UITraitSet_ClassReference/index.html

「iOS8のUITraitCollectionを使って、Adaptiveにインタフェイスを設計する!!」
と息巻いても、現実にはiOS6, iOS7のサポートも続けなくてはいけません。
そんなわけで、iOS7以前ではUIUserInterfaceIdiomを使う方法を考えてみました。あくまでも簡易的な方法ではありますが、僕の作っているアプリではなかなか便利に使えています。

#import <objc/message.h>

- (BOOL)isCompact
{
    SEL traitCollectionSelector = NSSelectorFromString(@"traitCollection");
    if(![self respondsToSelector:traitCollectionSelector]){
        // Do not support traitCollection
        return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone;
    }
    id traitCollection = objc_msgSend(self, traitCollectionSelector);
    SEL horizontalSizeClassSelector = NSSelectorFromString(@"horizontalSizeClass");
    NSInteger sizeClassNum = (NSInteger)objc_msgSend(traitCollection, horizontalSizeClassSelector);
    return sizeClassNum == 1; // UIUserInterfaceSizeClassCompact
}

- (BOOL)isRegular
{
    return !self.isCompact;
}

iOS8 SDKを参照しない状態でもビルドできるようにobjc_msgSendを使用しています。

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13