iOS常用第三方庫之Masonry
一、前言 關於蘋果的布局一直是我比較糾結的問題,是寫代碼來控制布局,還是使用storyboard來控制布局呢?以前我個人開發的時候很少使用代碼去寫約束,因為太麻煩了。所以最終選擇的都是AutoLayout進行布局,然後拖線設定約束。不過好多公司進行iOS開發的時候都會去動態修改約束,而且有的會使用約束去建立一些動畫,所以不太去用storyboard進行開發(還有就是使用storyboard幾個人合作的時候比較麻煩)。反倒更多的是寫代碼開發看起來更加的高效。所以好多開發人員都開始去使用Masonry。它是一個封裝的第三方類庫,作用就是來簡化開發人員寫布局約束。 二、“安裝”Masonry 因為它是一個第三方的類庫,我們可以從這裡下載,然後解壓將Masonry那個檔案夾拖入自己的專案檔夾下即可。 三、開始使用Masonry 我們在使用它的時候,最好在AppDelegate.m的 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;方法中去自訂載入自己的控制器。例如我寫的時候就是這樣:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.window.backgroundColor = [UIColor whiteColor]; UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc] init]]; self.window.rootViewController = nav; [self.window makeKeyAndVisible]; return YES;}
直接載入的我自己寫的ViewController。(建議把系統內建的Main.stoaryboard刪除掉,如果運行報錯自己修改,問題不大)。 先來一個不用Masonry寫的最簡單的布局:(目的是在視圖中添加一個視圖)
- (void)viewDidLoad { [super viewDidLoad]; self.title = @"Basic View"; UIView *view1 = [[UIView alloc] init]; view1.translatesAutoresizingMaskIntoConstraints = NO; view1.backgroundColor = [UIColor greenColor]; [superview addSubview:view1]; UIEdgeInsets padding = UIEdgeInsetsMake(74, 10, 10, 10); [superview addConstraints:@[ //view1 constraints [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeTop multiplier:1.0 constant:padding.top], [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeLeft multiplier:1.0 constant:padding.left], [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-padding.bottom], [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeRight multiplier:1 constant:-padding.right], ]];}