• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 基于UILabel的UICollectionViewCell AutoLayout动态高度

[复制链接]
菜鸟教程小白 发表于 2022-12-12 15:08:50 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在使用 UICollectionViewCell 的自动布局和大小类。所以我们的想法是制作一个与 Instagram 相似的 UI。

问题是我无法完全理解如何添加正确的自动布局,因为似乎添加缺少的约束并没有神奇地做到这一点。

enter image description here

当我添加约束时,即使没有警告,它总是在目标输出上显示“将尝试通过打破约束来恢复”。目标是根据 iphone 类型使配置文件单元动态,并根据 bioLabel 动态高度。现在我把它设为静态,这是非常错误的,因为当我使用这种方法时

systemLayoutSizeFittingSize:UILayoutFittingCompressedSize

它总是返回零,我猜是因为自动布局约束放错了位置。你能告诉我如何根据它的约束计算单元格的大小吗?我已经在 github 上创建了这个项目,任何帮助将不胜感激!

CollectionViewAutoLayout



Best Answer-推荐答案


我下载了您的代码并发现了问题。看,您只需在 collectionView:layout:sizeForItemAtIndexPath 方法中替换这行代码即可解决您的问题。

- (CGSize)collectionViewUICollectionView *)collectionView layoutUICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPathNSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        CGFloat height = [self findHeightForText"Description about yourself, who you are and what impact did you do to the environment. did you do to the environment. Description about yourself, who you are and what impact did you do to the environment. did you do to the environment. who you are and what impact did you do to the environment. did you do to the environment. who you are and what impact did you do to the environment. did you do to the environment." havingMaximumWidth:[UIScreen mainScreen].bounds.size.width andFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];
        return CGSizeMake([UIScreen mainScreen].bounds.size.width, 150 + height);
    }
    else {
        return CGSizeMake((([UIScreen mainScreen].bounds.size.width - 2.0) / 3.0), (([UIScreen mainScreen].bounds.size.width - 4.0) / 3.0));
    }
}

添加此方法动态计算高度。

 #pragma mark - Height Calculation Method
- (CGFloat)findHeightForTextNSString *)text havingMaximumWidthCGFloat)widthValue andFontUIFont *)font {
    CGSize size = CGSizeZero;
    if (text) {
        //iOS 7
        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes{ NSFontAttributeName:font } context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height + 1);
    }
    return size.height;
}

更换一次并在所有设备上进行测试,然后告诉我...希望对您有所帮助

关于ios - 基于UILabel的UICollectionViewCell AutoLayout动态高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29933364/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap