如何在UIListContentConfiguration中设置固定尺寸UIImage?reservedLayoutSize无效
我希望在单元格中设置固定尺寸的图片,以下是我在单元格中的代码:
var content = defaultContentConfiguration() content.image = img content.imageProperties.reservedLayoutSize = CGSize(width: 80, height: 80) self.contentConfiguration = content
设置reservedLayoutSize后并未生效,请问有什么解决方法吗?
解决方法
调整图片内容模式:默认图片会保持自身比例缩放,即便设置了固定尺寸,若图片比例与80x80不符,视觉上可能看起来没生效。手动指定内容模式:
content.imageProperties.contentMode = .scaleAspectFill // 若使用scaleAspectFill,开启裁剪避免图片超出范围 content.imageProperties.clipsToBounds = true也可根据需求选择
.scaleToFill强制拉伸填充尺寸。检查单元格布局约束:如果单元格的宽高被其他约束强制限制,会覆盖
reservedLayoutSize的设置。确保单元格没有固定高度/宽度的强约束,或图片区域的约束优先级低于配置的尺寸设置。改用自定义ImageView控制:如果默认配置的限制太多,直接在单元格中添加独立的UIImageView并设置约束/frame:
let imageView = UIImageView(image: img) imageView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(imageView) NSLayoutConstraint.activate([ imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16), imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor), imageView.widthAnchor.constraint(equalToConstant: 80), imageView.heightAnchor.constraint(equalToConstant: 80) ]) imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true确认iOS版本兼容性:
reservedLayoutSize是iOS 14及以上的API,若项目需兼容更低版本,该属性不会生效,需用传统约束方式设置图片尺寸。
内容的提问来源于stack exchange,提问作者yxk
相关产品推荐
相关产品推荐

