swift2.0 cell在一定宽度限制下的高度自适应

效果图:


高度自适应网上有很多,但是我遇到的是宽度有限制的高度自适应,所以准备记录一下这个搞了一天多的适应方法……直接上代码

首先是在tableview的界面控制器中添加上这两个cell高度计算函数

    func tableView(tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {//预估高度,据说加了之后能提高计算cell高度的效率
        return 200.0
    }
    
    //UITableViewDelegate
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {//实际高度
        let index=indexPath.row
        let data=self.dataSource[index] as! NSDictionary
        return OrderCell.cellHeight(data)
    }
然后在cell的控制器中,添加高度计算函数:

//公开方法
    class func cellHeight(data: NSDictionary) -> CGFloat {
        var h: CGFloat = 0.0
        var detail = " "
        
        let c11 = data["cloth11"] as? Int
        if  c11 != nil {
            detail += "小袋x"+c11!.description+"、"
        }
        let c12 = data["cloth12"] as? Int
        if c12 != nil {
            detail += "中袋x"+c12!.description+"、"
        }
        let c13 = data["cloth13"] as? Int
        if c13 != nil {
            detail += "大袋x"+c13!.description+"、"
        }
        let c14 = data["cloth14"] as? Int
        if c14 != nil {
            detail += "超大袋x"+c14!.description+"、"
        }
        let c21 = data["cloth21"] as? Int
        if c21 != nil {
            detail += "春秋款x"+c21!.description+"、"
        }
        let c22 = data["cloth22"] as? Int
        if c22 != nil {
            detail += "夏薄款x"+c22!.description+"、"
        }
        let c23 = data["cloth23"] as? Int
        if c23 != nil {
            detail += "冬厚款x"+c23!.description+"、"
        }//根据data取得textView的内容
        //textview高度计算方法
        let font = UIFont.systemFontOfSize(15)//确定textview的字体大小
        
        let style = NSMutableParagraphStyle()
        style.lineBreakMode = NSLineBreakMode.ByCharWrapping//确定textView的换行方式是按照字母的个数来确定是否换行
        
        
        let attributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: style.copy()];
        
        let size = CGSizeMake(kCellWidth - 174, CGFloat.max)//根据约束确定textView的宽度限制
        let text = detail as NSString//self.label_content.text! as NSString
        let rect = text.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)//sizeWithAttributes(attributes)
        //计算在宽度限制和字体大小限制下textView的高度
        h = rect.size.height + 21.0 + 31.0 + 27.0 + 16.0 + 1.0 + 30.0
        //h = h + height
        return rect.size.height == 18.0 ? 109.0 : h//如果textView只有一行那么返回根据约束计算出来的高度,如果大于等于两行,那么返回计算出的高度
    }

以上代码基本能实现宽度限制下的高度自适应,但是这依赖于xib文件中的约束,基本原则就是左右上下的约束都要规定好,一些内容不会变的控件的宽高可以定死,这样方便cell的整体高度~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值