寫給自己---iOS開發技巧_圖片裁剪及cell自適應

??? 現在似乎很多公司已經開始接受和使用Storyboard(簡稱SB),關于其中AutoLayout,開始學習的時候確實有很多不了解,經過自己的惡補,勉勉強強也算是精通了.

? ? 關于一些基礎的AutoLayout的知識就不再贅述了,這里記錄一下自己測試Demo時候需要注意到的技術點:那就是UITableViewCell的AutoLayout,傳說中的自適應.

??? 關于自適應,其實還是有多種方法可以達到的.例如計算image或label的高度,以及寬高比例,返回回去.


-(void)requestDataForReloadWithUrl:(NSString * )url Block:(SetImage)block

{

NSMutableArray * arraydata = [NSMutableArray arrayWithCapacity:10];

dispatch_async(dispatch_get_global_queue(0, 0), ^{

NSURL *url_Url = [NSURL URLWithString:url];

NSURLSession *session = [NSURLSession sharedSession];

NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url_Url];

NSURLSessionDataTask *task =[session dataTaskWithRequest:requset completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

if (data != nil) {

NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

NSArray * array = dic[@"body"][@"slides"];

for (NSDictionary * dic in array) {

CellHeightModel * model = [[CellHeightModel alloc]init];

// 存儲圖片路徑

model.image = dic[@"image"];

// 等比縮放之后的高度

/**

*? 根據屏幕的寬高比例去計算寬高比例 求出等比縮放之后的高度

X : 屏幕寬度 = 圖片高度 : 圖片寬度

X 縮放之后的高度

*/

CGFloat imageWidth = [dic[@"width"] floatValue];

CGFloat imageHeight = [dic[@"height"] floatValue];

CGFloat height = [UIScreen mainScreen].bounds.size.width * imageHeight / imageWidth;

model.height = height;

// 文本

model.kDescription = dic[@"description"];

// 文本高度

CGRect rect = [self getStringCGrectFromString:dic[@"description"]];

CGFloat textHeight = rect.size.height;

model.kDescriptionHeight = textHeight;

// cell單元格高度

model.cellHeight = model.height + model.kDescriptionHeight;

[arraydata addObject:model];

}

}

dispatch_async(dispatch_get_main_queue(), ^{

//在主線程中進行block結果回調

if (block) {

block(arraydata);

}

});

}];

[task resume];

});

}

-(CGRect)getStringCGrectFromString:(NSString *)str

{

/**

*? (主要是將被iOS7 Deprecated的sizeWithFont:constrainedToSize:lineBreakMode:方法改成了boudingRectWithSize:options:attributes:context:方法來計算文本尺寸)

*

*? @param mainScreen.bounds.size.width? 屏幕寬度

*? @param 10000.0f? ? ? ? ? ? ? ? ? ? ? 最大高度

*

*? @return 當前文本的矩形

*/

CGRect? rect = [str boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 10000.0f) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17.5] forKey:NSFontAttributeName] context:nil];

return rect;

}

在cell.m文件中

-(void)setCellmodel:(CellHeightModel *)cellmodel

{

// 獲取當前 cellHeightImg 的所有約束條件

//? ? NSArray* constrains = self.cellHeightImg.constraints;

//? ? // 遍歷當前 cellHeightImg 的所有約束條件

//? ? for (NSLayoutConstraint* constraint in constrains) {

//? ? ? ? // 判斷約束條件是否等于 高的約束條件

//? ? ? ? if (constraint.firstAttribute == NSLayoutAttributeHeight) {

//? ? ? ? ? ? // 修改約束條件中的高

//? ? ? ? ? ? constraint.constant = cellmodel.imageNameHeight;

//? ? ? ? }

//? ? }

/**

*? 其中的firstItem與secondItem分別是界面中受約束的視圖與被參照的視圖。他們不一定非得是兄弟關系或者父子關系,只要是他們有著共同的祖先視圖即可,這一點是autoresizingMask無法做到的。

*** 在 UIView 中有一個autoresizingMask的屬性,它對應的是一個枚舉的值(如下),屬性的意思就是自動調整子控件與父控件中間的位置,寬高

firstAttribute與secondAttribute分別是firstItem與secondItem的某個布局屬性(NSLayoutAttribute):

*/

self.imgOfCellHeight.constant = cellmodel.height;

[self.cellHeightImg sd_setImageWithURL:[NSURL URLWithString:cellmodel.image]];

[self.cellHeightTextLable setText:cellmodel.kDescription];

}


最后在controller中調用

#pragma mark - 設置高度

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

// 從模型中取出當前cell的高度

CellHeightModel * cellModel = self.arrayData[indexPath.row];

return cellModel.cellHeight;

}

需要注意的是這個Demo是需要通過操作xib文件,拖動約束實現的




??? 為什么要畫出三條線呢,下面要說到的就是第二種方法了,代碼量根本不是一個級別的,同時也點到了圖片裁剪


??? 例如此圖,需求為圖片等比例縮放,下面的新聞描述自適應高度.

??? 我們完全可以通過操作xib,再加上那么幾個小小的方法完成.

???

??? 將imageView的約束條件設置為 上 0,左右 0,下 10; ?


label的約束條件則為左右 0,下10

//從model獲取數據

-(void)loadDataWithModel:(CellModel *)model

{

UIImage *temp = model.img;

if (model.img.size.width > [UIScreen mainScreen].bounds.size.width) {

float scale = model.img.size.width / [UIScreen mainScreen].bounds.size.width;

float height = model.img.size.height/scale;

CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, height);

temp = [self imageWithImageSimple:model.img scaledToSize:size];

}

self.img.image = temp;

self.img.contentMode = UIViewContentModeScaleAspectFit;

self.detailLabel.text = model.descrip;

}

重點就是這兩個方法

#pragma mark - 裁剪圖片

- ( UIImage *)imageWithImageSimple:( UIImage *)image scaledToSize:( CGSize )newSize

{

// Create a graphics image context

UIGraphicsBeginImageContext (newSize);

// Tell the old image to draw in this new context, with the desired

// new size

[image drawInRect : CGRectMake ( 0 , 0 ,newSize. width ,newSize. height )];

// Get the new image from the context

UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext ();

// End the context

UIGraphicsEndImageContext ();

// Return the new image.

return newImage;

}

然后再控制器調用此方法就OK了!

self.tableView.estimatedRowHeight = 44;

self.tableView.rowHeight = UITableViewAutomaticDimension;

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容