วันจันทร์ที่ 8 กรกฎาคม พ.ศ. 2556

IOS 6

การเพิ่ม interface(.xib) ใน Storyboard โดยสามารถกำหนดได้ทั้งแนวตั้ว - นอน [Landscape, Portrait]

ขั้นตอนที่ 1.

สร้างโปรเจทใหม่บน XCode เลือกสร้างแบบ Single View

ขั้นตอนที่ 2.

คลิ๊กเลือก Item บน Storyboard (i-Phone หรือ i-Pad)

ขั้นตอนที่ 3.

คลิ๊กขวา New File -> User Interface -> View จะได้ View.xib ขึ้นมา จากนั้นเราก็สามารถ เพิ่ม View เข้าไปกี่ View ก็ได้วิธีการดึง View แต่ละ View มาใช้

 NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"ชื่อ View" owner:self options:nil]; 

สมมุติเรามี 2 view items(คือ View ที่เราเพิ่มลง ใน View.xib [Landscape, Portrait])
สามารถเข้าถึงแต่ละ View items ได้โดย

[subviewArray objectAtIndex:0]
[subviewArray objectAtIndex:1]

Source Code

 //////////////////////// .h  //////////////////////////// 

@interface ViewController : UIViewController
{
  
    IBOutlet UIView *portraitView, *landscapeView;
  
    NSArray *subviewArray;
  
}

@property (nonatomic, retain) IBOutlet UIView *portraitView;
@property (nonatomic, retain) IBOutlet UIView *landscapeView;
@property (nonatomic, retain) IBOutlet NSArray *subviewArray;

@end


 //////////////////////// .m  ////////////////////////////

@implementation ViewController

@synthesize landscapeView, portraitView, subviewArray;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
   
    // Nib File return array subview : refer  = http://stackoverflow.com/questions/5354653/adding-a-custom-subview-created-in-a-xib-to-a-view-controllers-view-what-am
   // จะได้ View ทั้งหมดที่อยู่ใน .xib มา
    subviewArray = [[NSBundle mainBundle] loadNibNamed:@"test" owner:self options:nil];

   
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:@"UIDeviceOrientationDidChangeNotification" object:nil];
}

- (void) orientationChanged:(id)object
{
    UIInterfaceOrientation interfaceOrientation = [[object object] orientation];
   
    if (interfaceOrientation == UIInterfaceOrientationPortrait ||
        interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {

        // แนวตั้ว
        [self.view addSubview:[subviewArray objectAtIndex:0]];
    }
    else
    {
        // แนวนอน
        [self.view addSubview:[subviewArray objectAtIndex:1]];
    }
}

@end


Source Code
https://www.dropbox.com/s/ij82uym2f021z3i/OrientationTutorial.zip





ไม่มีความคิดเห็น:

แสดงความคิดเห็น