使用sdwebimage在表格视图中动态图像高度



我想在表格视图中显示动态高度图像,图像来自网址,所以我正在使用sdwebimage。 后台线程中的 Sdwebimage 设置图像。

[self.imageView sd_setImageWithURL:[NSURL URLWithString: encodedurl1]  completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];

我正在更新此线程中图像视图的约束高度。

[self.imageView sd_setImageWithURL:[NSURL URLWithString: encodedurl1]  completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
CGFloat multiplier = (CGRectGetWidth(self.imageView.bounds) / image.size.width);
[self.imageViewHeightConstraint setConstant:multiplier * image.size.height];
}];

这段代码对我很有帮助,但我在后台线程中获得了图像大小 所以,我花点时间来更新约束图像视图的高度

我最近两天正在搜索和护目镜。 这种类型的问题得到了许多开发人员,但在堆栈溢出的任何问题中都没有答案。

像在主线程中一样进行更新

[self.imageView sd_setImageWithURL:[NSURL URLWithString: encodedurl1]  completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
dispatch_async(dispatch_get_main_queue(), ^{
CGFloat multiplier = (CGRectGetWidth(self.imageView.bounds) / image.size.width);
[self.imageViewHeightConstraint setConstant:multiplier * image.size.height];
[self setNeedsUpdateConstraints];
});
}];

试试这个为我的项目创建的帮助程序方法。

-(void)imageWithURL:(NSURL *)imageurl WithIndexPath:(NSIndexPath *)indexpath WithCallback:(void(^)(UIImage *downloadedImage,BOOL isCache , NSIndexPath *imageIndexPath))callback{
if (![[SDWebImageManager sharedManager ]diskImageExistsForURL:imageurl]) {
[[SDWebImageManager sharedManager]downloadImageWithURL:imageurl options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
// resize image here
callback(image , NO,indexpath);
}];
}
else{
UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:[imageurl absoluteString]] ;
// resize image here
callback(image, YES ,indexpath);
}
}

在cellForRowAtIndexPath中调用此方法

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self imageWithURL:[NSURL URLWithString:objPreparations.strImageURL] WithIndexPath:indexPath WithCallback:^(UIImage *downloadedImage, BOOL isCache, NSIndexPath *imageIndexPath) {
if (downloadedImage) {
dispatch_async( dispatch_get_main_queue(), ^{
UITableViewCell  *existcell = [tableView cellForRowAtIndexPath:imageIndexPath];
if (existcell) {
// assign image to cell here
[tableView reloadRowsAtIndexPaths:@[imageIndexPath] withRowAnimation:UITableViewRowAnimationNone];
}
});
}
}];
});

不要忘记

在视图中DidLoad

tblView.estimatedRowHeight = 44.0 ;
tblView.rowHeight = UITableViewAutomaticDimension;

并且还为图像视图提供顶部,底部,前导,尾随约束,并为图像视图提供大于相等高度的约束

最新更新