【发布时间】:2016-01-27 04:37:20
【问题描述】:
我有一个自定义的UITableViewCell,它具有动态图像高度。创建单元格时,所有调整大小的工作都按预期进行。问题是一旦单元格被UITableView 重用,图像高度的约束就会改变,并导致“无法同时满足约束”错误。
我尝试在重置之前停用高度限制,但它仍然会导致错误。
关于设置高度锚。这每次都会创建一个新实例,是否从内存中释放了停用的约束?有没有办法以这种格式更新当前约束?
我应该在 - (void)prepareForReuse 方法中做些什么吗?
感谢您的帮助
// Within Custom UITableViewCell
// The cell is a prototype cell in StoryBoard
// The width of the image is fixed and already set
// Observe when the image is set for imgView
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"image"]) {
if(self.imgView.image) {
CGFloat ratio = self.imgView.image.size.height / self.imgView.image.size.width;
self.imageHeightConstraint.active = NO;
self.imageHeightConstraint = [self.imgView.heightAnchor constraintEqualToAnchor:self.imgView.widthAnchor multiplier:ratio];
self.imageHeightConstraint.identifier = @"imageHeightConstraint";
self.imageHeightConstraint.active = YES;
}
}
}
UITableViewCell 自动调整大小,因为 UIImageView 在 UIStackView 中,其顶部和底部锚点固定在单元格 contentView 的顶部和底部。
- (void)buildUI {
UIStackView *containerStackView = [UIStackView new];
[self.contentView addSubview:containerStackView];
containerStackView.translatesAutoresizingMaskIntoConstraints = NO;
containerStackView.axis = UILayoutConstraintAxisHorizontal;
containerStackView.distribution = UIStackViewDistributionFill;
containerStackView.alignment = UIStackViewAlignmentCenter;
containerStackView.spacing = 10;
[containerStackView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:10.0].active = YES;
[containerStackView.centerXAnchor constraintEqualToAnchor:self.contentView.centerXAnchor].active = YES;
[containerStackView.widthAnchor constraintEqualToAnchor:self.contentView.widthAnchor multiplier:kImageWidthMultiplier].active = YES;
[containerStackView.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-30.0].active = YES;
self.imgView = [UIImageView new];
[containerStackView addArrangedSubview:self.imgView];
self.imgView.translatesAutoresizingMaskIntoConstraints = NO;
[self.imgView.widthAnchor constraintEqualToAnchor:containerStackView.widthAnchor multiplier:0.492].active = YES;
}
【问题讨论】:
-
当你改变imageView的高度时,你是否也在增加UITableViewCell的高度?
self.imageHeightConstraint是weak还是strong属性? -
是的,
UITableViewCell自动调整大小以适合图像。self.imageHeightConstraint有一个weak引用。 -
尝试将其保留为
strong,因为在停用约束后它可能是nil。 -
我已经尝试过了,没有任何区别。
标签: ios objective-c uitableview autolayout