gpt4 book ai didi

ios - 如何动态设置 UIView 约束?

转载 作者:行者123 更新时间:2023-11-29 10:31:23 57 4
gpt4 key购买 nike

我有一个自定义 UITableViewCell。它从上到下包含标签和 UIImageViews。我向标签和 UIImageViews 添加了约束。所以我可以使用 systemLayoutSizeFittingSize: UILayoutFittingCompressedSize 来计算适合内容的单元格高度。但是 UIImageView 中的图像是使用 SDWebImage 从网上加载的。首先我可以为 UIImageView 设置一些约束。加载图像时,我应该更改 UIImageView 的约束以满足其大小。但有时会发生错误。有时候没问题:

* Assertion failure in -[NSLayoutConstraint _setSymbolicConstant:constant:], /SourceCache/Foundation_Sim/Foundation-1142.14/Layout.subproj/NSLayoutConstraint.m:585 2015-04-01 19:57:44.537 HiPDA[3760:63583]
*
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Constant is not finite! That's illegal. constant:nan'
*** First throw call stack:
(
0 CoreFoundation 0x00000001113cfa75 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000111068bb7 objc_exception_throw + 45
2 CoreFoundation 0x00000001113cf8da +[NSException raise:format:arguments:] + 106
3 Foundation 0x000000010ef0cb6f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
4 Foundation 0x000000010ee87c7d -[NSLayoutConstraint _setSymbolicConstant:constant:] + 149

代码是:

__weak typeof(self) weakSelf = self;
__weak typeof(UIImageView *) weakImgView=imgView;
[imgView sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:THREADLISTDETAILIMAGE]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

CGFloat width=image.size.width>maxWidth?maxWidth:image.size.width;
NSLayoutConstraint *imgW1=[NSLayoutConstraint constraintWithItem:weakImgView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:0.0 constant:width];
[weakSelf.contentView addConstraint:imgW1];
NSLayoutConstraint *imgH1=[NSLayoutConstraint constraintWithItem:weakImgView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:0.0 constant:width*image.size.height/image.size.width];
[weakSelf.contentView addConstraint:imgH1];

[weakSelf needsUpdateConstraints];
[weakSelf layoutIfNeeded];
[weakSelf layoutSubviews];
}];

如果图片下载完成,tableview 不会刷新。我可以看到图像来自单元格大小。我该如何解决?

最佳答案

您必须为 imageView 使用 Outlet NSLayoutConstraint 并以编程方式更改值,例如

self.imgViewHeightConstraint.constant = 300(一些值)

关于ios - 如何动态设置 UIView 约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29390313/

57 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com