1. 程式人生 > >iOS自動佈局實現Cell和Tableview高度自適應(SDAutoLayout)

iOS自動佈局實現Cell和Tableview高度自適應(SDAutoLayout)

SDAutoLayout

一行程式碼搞定自動佈局!致力於做最簡單易用的Autolayout庫。The most easy way for autolayout.

   ☆新增:cell高度自適應 + label文字自適應☆

>>>>> tableview cell 自動高度設定只需要3步

1. >> 設定cell高度自適應:
// cell佈局設定好之後呼叫此方法就可以實現高度自適應(注意:如果用高度自適應則不要再以cell的底邊為參照去佈局其子view)
[cell setupAutoHeightWithBottomView:_view4 bottomMargin:10];

2. >> 設定 tableview 資料來源和代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// 2.1 註冊模型cell 
[self.tableView startAutoCellHeightWithCellClass:“cell類名” contentViewWidth:“contentview寬度”];

return _rowCount;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 2.2 根據模型取得cell高度
return [self.tableView cellHeightForIndexPath:indexPath model:“model” keyPath:@"model屬性名"];
}

*********** 普通view的自動佈局講解 ***********  

   摒棄複雜累贅的約束,利用執行時Runtime在合適的時機佈局檢視。

0.用法示例

/* 用法一 */
_view.sd_layout
.leftSpaceToView(self.view, 10)
.topSpaceToView(self.view, 80)
.heightIs(130)
.widthRatioToView(self.view, 0.4);  

/* 用法二 (一行程式碼搞定,其實用法一也是一行程式碼) */
_view.sd_layout.leftSpaceToView(self.view, 10).topSpaceToView(self.view,80).heightIs(130).widthRatioToView(self.view, 0.4);


>> UILabel文字自適應:
// autoHeightRatio() 傳0則根據文字自動計算高度(傳大於0的值則根據此數值設定高度和寬度的比值)
_label.sd_layout.autoHeightRatio(0);

*******************************************************************************

    注意:先把需要自動佈局的view加入父view然後在進行自動佈局,例: 

    UIView *view0 = [UIView new];
    UIView *view1 = [UIView new];
    [self.view addSubview:view0];
    [self.view addSubview:view1];

    view0.sd_layout
    .leftSpaceToView(self.view, 10)
    .topSpaceToView(self.view, 80)
    .heightIs(100)
    .widthRatioToView(self.view, 0.4);

    view1.sd_layout
    .leftSpaceToView(view0, 10)
    .topEqualToView(view0)
    .heightRatioToView(view0, 1)
    .rightSpaceToView(self.view, 10);
*******************************************************************************

1.用法簡析

1.1 > leftSpaceToView(self.view, 10)

方法名中帶有“SpaceToView”的方法表示到某個參照view的間距,需要傳遞2個引數:(UIView)參照view 和 (CGFloat)間距數值

1.2 > widthRatioToView(self.view, 1)

方法名中帶有“RatioToView”的方法表示view的寬度或者高度等屬性相對於參照view的對應屬性值的比例,需要傳遞2個引數:(UIView)參照view 和 (CGFloat)倍數

1.3 > topEqualToView(view)

方法名中帶有“EqualToView”的方法表示view的某一屬性等於參照view的對應的屬性值,需要傳遞1個引數:(UIView)參照view

1.4 > widthIs(100)

方法名中帶有“Is”的方法表示view的某一屬性值等於引數數值,需要傳遞1個引數:(CGFloat)數值

PS:

和Masonry有什麼異同?

1.程式碼更簡潔,方法語義更直觀,可以更快佈局

2.效能方面和masonry相當,某些情況下效能還要優於masonry