本文的屬性也不知道是原創還是摘抄了,一個同僚正在學橫豎屏自适應的東西,剛看到用代碼調整的部分,然後我徒手給實作了用IB實作的方式,估計書上應該都有,隻是我沒看吧。
簡單來說就兩種方式:代碼實作和IB實作
原理都是通過判斷方向旋轉然後給出相應的調整方式。
效果圖:
代碼實作:
ViewController.h
@property (nonatomic,retain)IBOutlet UIButton *button1;
@property (nonatomic,retain)IBOutlet UIButton *button2;
@property (nonatomic,retain)IBOutlet UIButton *button3;
@property (nonatomic,retain)IBOutlet UIButton *button4;
@property (nonatomic,retain)IBOutlet UIButton *button5;
@property (nonatomic,retain)IBOutlet UIButton *button6;
做幾個連接配接變量,要和界面上對應的按鈕連接配接起來
ViewController.h
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration{
if (toInterfaceOrientation == UIInterfaceOrientationPortrait ||toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
button1.frame = CGRectMake(20, 20, 125, 125);
button2.frame = CGRectMake(175, 20, 125, 125);
button3.frame = CGRectMake(20, 168, 125, 125);
button4.frame = CGRectMake(175, 168, 125, 125);
button5.frame = CGRectMake(20, 315, 125, 125);
button6.frame = CGRectMake(175, 315, 125, 125);
}else{
button1.frame = CGRectMake(20, 20, 125, 125);
button2.frame = CGRectMake(20, 155, 125, 125);
button3.frame = CGRectMake(177, 20, 125, 125);
button4.frame = CGRectMake(177, 155, 125, 125);
button5.frame = CGRectMake(328, 20, 125, 125);
button6.frame = CGRectMake(328, 155, 125, 125);
}
}
增加一個方向适應函數。我覺得最麻煩的就是這個代碼調位置,然後就齊活了。
IB實作:
ViewController.xib
實作兩個View,分别對應橫屏和豎屏
ViewController.h
@interface ViewController : UIViewController{
IBOutlet UIView *protView;
IBOutlet UIView *landView;
}
增加兩個連接配接變量,分别對應橫屏和豎屏
ViewController.m
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
// Return YES for supported orientations
if (interfaceOrientation == UIInterfaceOrientationPortrait ||
interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown ) {
self.view = protView;
}
else{
self.view = landView;
}
return YES;
}
當方向改變時自動選擇對應的view,that’s all!
讨論:對于使用哪種方式,筆者還是傾向使用IB,雖然用代碼的方式看起來比較酷,也有代碼控說這樣寫着比較爽。我想說的的,面對複雜的應用環境,需求天天變,界面天天調,如果用代碼的話,死的心都會有的。再說MVC這麼酷的架構幹嘛不用?
源代碼下載下傳:
AutosizeCode
AutosizeView