效果图:
高度自适应网上有很多,但是我遇到的是宽度有限制的高度自适应,所以准备记录一下这个搞了一天多的适应方法……直接上代码
首先是在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的整体高度~
4311

被折叠的 条评论
为什么被折叠?



