iOS自動佈局和UITableViewCell
阿新 • • 發佈:2019-02-05
1、自動佈局
- 一個UI控制元件使用自動佈局可以只設置上邊距(Top space)、下邊距(Bottom speace)、左邊距(Leading Space)、右邊距(Trailing space);
- 對齊一般是要同時選中兩個控制元件(commond+滑鼠)
- UILabel 如果要自動換行需要設定Lines屬性為0,上下左右邊距固定
- 如果自動約束設定錯誤,編譯後提示視窗會告訴你時那個控制元件有問題
2、自定義UITableViewCell
- 預設cell的設計檢視寬度是320pt
- 如果在
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
postCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"postCell"];
if (cell ==nil ){
cell = [[[NSBundle mainBundle] loadNibNamed:@"postCell" owner:self options:nil] objectAtIndex:0];
}
NSInteger row = indexPath.row;
NSMutableDictionary *d = [aryData objectAtIndex:row];
cell.lbCreateTime.text = [d valueForKey:@"createtime" ];
cell.lbNickName.text = [d valueForKey:@"createtime"] ;
cell.lbUserGroupName.text = [d valueForKey:@"usergroup"] ;
cell.lbAgeAndCountryAndCity.text = [NSString stringWithFormat:@"%@ %@ %@",[d valueForKey:@"age"], [d valueForKey:@"country"],[d valueForKey:@"city"],nil];
cell.lbContent .numberOfLines = 0;
cell.lbContent.lineBreakMode = NSLineBreakByClipping;
cell.lbContent.text = [d valueForKey:@"content"];
cell.imgContent.image = [UIImage imageNamed:@"heaerpic.jpg"];
return cell;
}
從xib裡面建立cell不需要再使用initWithStyle方法建立,類似這樣:
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"doctorView" owner:self options:nil];
id oneObject = [nib objectAtIndex:0];
cell = [(dotorCell *)oneObject initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
這樣的程式碼會導致cell寬度固定為320pt,沒法適配ipone6s
- 如果cell高度沒法自動計算就需要手工計算
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//return UITableViewAutomaticDimension;
NSMutableDictionary *d = [aryData objectAtIndex:indexPath.row];
postCell *cell = (postCell *)self.prototypeCell;
//獲得當前cell高度
CGRect frame = [cell frame];
//文字賦值
cell.lbContent.text = [d valueForKey:@"content"];
//設定label的最大行數
cell.lbContent.numberOfLines = 0;
CGSize size = CGSizeMake(300, 1000);
CGSize labelSize = [cell.lbContent.text sizeWithFont:cell.lbContent.font constrainedToSize:size lineBreakMode:NSLineBreakByClipping];
//NSLog(@"height is %f",cell.lbContent.frame.size.height+cell.lbContent.frame.origin.y);
//return cell.lbContent.frame.size.height+cell.lbContent.frame.origin.y;
return labelSize.height+cell.lbContent.frame.origin.y+cell.imgContent.frame.size.height+cell.btnLike.frame.size.height+5;
//return 180.0f;
}
注意如果UILabel 是自動適應高度的,需要再計算一次它的高度