您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

iOS 邊練邊學:介紹布局的三種方法

編輯:iOS 程式設計技術

使用程式碼實現 Autolayout 的方法 1 —— 建立約束

+(id)constraintWithItem:(id)view1

attribute:(NSLayoutAttribute)attr1

relatedBy:(NSLayoutRelation)relation

toItem:(id)view2

attribute:(NSLayoutAttribute)attr2

multiplier:(CGFloat)multiplier

constant:(CGFloat)c;

* view1:要約束的控件

* attr1:約束的類型(做怎樣的約束)

* relation:與參照控件之間的關係

* view2:參照的控件

* attr2:約束的類型(做怎樣的約束)

* multiplier:乘數

* c:常量

—— 加入約束

- (void)addConstraint:(NSLayoutConstraint *)constraint;

- (void)addConstraints:(NSArray *)constraints;

—— 注意

- 一定要在擁有父控件之後再加入約束

- 關閉 Autoresizing 功能:view.translatesAutoresizingMaskIntoConstraints = NO;

使用程式碼實現 Autolayout 的方法 2 —— VFL

—— 使用 VFL 建立約束陣列

+ (NSArray *)constraintsWithVisualFormat:(NSString *)format

options:(NSLayoutFormatOptions)opts

metrics:(NSDictionary *)metrics

views:(NSDictionary *)views;

* format:VFL 語句

* opts:約束類型

* metrics:VFL 語句中用到的具體數值

* views:VFL 語句中用到的控件

—— 使用下面的巨集來自動生成 views 和 metrics 參數

NSDictionaryOfVariableBindings(...)

使用程式碼實現 Autolayout 的方法 3 —— Masonry

—— 使用步驟

- 加入 Masonry 資料夾的所有原始碼到專案中

- 加入 2 個巨集、匯入主標頭檔:

// 只要加入了這個巨集,就不用帶 mas_ 前綴

#define MAS_SHORTHAND

// 只要加入了這個巨集,equalTo 就等價於 mas_equalTo

#define MAS_SHORTHAND_GLOBALS

// 這個標頭檔一定要放在上面兩個巨集的後面

#import "Masonry.h"

—— 加入約束的方法

// 這個方法只會加入新的約束

[view makeConstraints:^(MASConstraintMaker *make) {

}];

// 這個方法會把以前的所有約束刪掉,加入新的約束

[view remakeConstraints:^(MASConstraintMaker *make) {

}];

// 這個方法將會覆蓋以前的某些特定的約束

[view updateConstraints:^(MASConstraintMaker *make) {

}];

—— 約束的類型

1. 尺寸:width/height/size

2. 邊界:left/leading/right/trailing/top/bottom

3. 中心點:center/centerX/centerY

4. 邊界:edges

—— tableView 如何顯示數據

- 設定 dataSource 資料來源

- 資料來源要遵守 UITableViewDataSource 協定

- 資料來源要實作協定中的某些方法

/**
* 告訴 tableView 一共有多少組數據
*/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

/**
* 告訴 tableView 第 section 組有多少行
*/
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

/**
* 告訴 tableView 第 indexPath 行顯示怎樣的 cell
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

/**
* 告訴 tableView 第 section 組的頭部標題
*/
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

/**
* 告訴 tableView 第 section 組的尾部標題
*/
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved