cell根据字多少返回高度--swift版

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "cellId")

        var  cellFrame = cell.frame

        cell.detailTextLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail

        let maxiNumlinSize = CGSizeMake(KEY_SCREEN_SIZE.width, 300)

        let rect:CGSize = (cell.detailTextLabel?.sizeThatFits(maxiNumlinSize))!

        cellFrame.size.height = rect.height + 60

        cell.frame = cellFrame

        return cell

 }




   func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {


        let cell:UITableViewCell = self.tableView(tableView, cellForRowAtIndexPath: indexPath)

        return cell.frame.size.height


    }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Swift 中,要根据文字内容自动撑开 UICollectionViewCell高度,可以使用 UICollectionViewDelegateFlowLayout 协议中的方法 `sizeForItemAt` 来实现。 具体实现步骤如下: 1. 计算文字内容所需的高度,可以使用 NSString 的方法 `boundingRect`,代码如下: ``` let text = "这是要显示的文字内容" let width = collectionView.bounds.width - 20 // 减去 cell 左右间距 let font = UIFont.systemFont(ofSize: 16) // 设置体大小 let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) let attributes = [NSAttributedString.Key.font: font] let textRect = NSString(string: text) .boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) ``` 2. 根据计算出的文字内容高度返回对应的 cell 高度,需要加上 cell 上下间距和文字内容与 cell 上下边距的总和,代码如下: ``` func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let text = "这是要显示的文字内容" let width = collectionView.bounds.width - 20 // 减去 cell 左右间距 let font = UIFont.systemFont(ofSize: 16) // 设置体大小 let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) let attributes = [NSAttributedString.Key.font: font] let textRect = NSString(string: text) .boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) let cellHeight = textRect.height + 20 + 10 // 20 为 cell 上下间距,10 为文字内容与 cell 上下边距的总和 return CGSize(width: width, height: cellHeight) } ``` 这样就可以自动撑开 UICollectionViewCell高度了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值