天天看點

iphone4、4S程式如何相容Iphone5 (關鍵字 NSLayout、NSLayoutConstraint)

1.首先記錄如何讓程式相容iphone5,很容易搜尋到,此處簡單記錄。

1.xib中use Autolayout勾上 2.xib中Size--Retina 4 Full Screen 3.代碼中判斷是否是iphone5:---- #define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO) 代碼控制,如:

if(iPhone5)

    {

    }else{

         CGRect rect = tabControllerHome.view.frame;

        rect.size.height = rect.size.height +88;

        tabControllerHome.view.frame = rect;

    }

2.其次,也是重點是XIB布局問題,Layout和NSLayoutConstraint

由于多控件的螢幕分辨率轉成“Retina 4 Full Screen”的螢幕分辨率,IOS6會有自動的Constraints。可能有的控件可能達不到效果,比如動态資料的ScrollView,動态高度的ImageView。此處需要學習Layout的Constraint入門,下面有兩篇很好的(Layout)入門文章:

http://www.raywenderlich.com/zh-hans/22873/ios-6-自動布局-入門-1

http://www.raywenderlich.com/zh-hans/23026/ios-6-自動布局-入門-2

如果仔細閱讀上面文章,按照它修改XIB在布局中的位置或高度等還會有code無法控制UIController的情況出現,

首先檢查XIB中的Constraints是否與code沖突,會動态改變的控件盡量不要寫死,根據需求擺放控件在布局中的位置,

其次,如果控件的constraint在code中依舊無法控制動态修改,可以不用驚慌,因為還有NSLayoutConstraint類,下面亮出寫法如:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.imageViewPanel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:imageViewPanel.frame.size.height]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeTop multiplier:1.0 constant:label.frame.origin.y]];

以此能達到動态顯示控件的效果