无法动态处理单元格大小,根据内容大小

时间:2016-11-01 05:03:10

标签: swift string uitableview uifont

我正在尝试根据内容大小动态更改tableView单元格高度,但是收到错误。

错误 -

enter image description here

实际代码 -

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        let height:CGFloat = self.calculateHeightForString(downloadTableDataa[indexPath.row] as! String)
        return height + 70.0
    }

    func calculateHeightForString(inString:String) -> CGFloat
    {
        let messageString = inString
        let attributes =  UIFont.init(name: "Roboto-Regular", size: 15)

        let attrString:NSAttributedString? = NSAttributedString(string: messageString, attributes: attributes)
        let rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(300.0,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil )//hear u will get nearer height not the exact value
        let requredSize:CGRect = rect
        return requredSize.height  //to include button's in your tableview

    }

1 个答案:

答案 0 :(得分:0)

问题在于您尝试将UIFont类型的对象传递到属性字段中,而属性字段需要一个类型为[String:AnyObject]的字典。那是错误告诉你的。

<强>之前

let attributes = UIFont.init(name:"Roboto-Regular", size:15.0) <---- UIFont
let attrString:NSAttributedString? = NSAttributedString(string: messageString, attributes: attributes) <---- wants a dictionary of type [String:AnyObject]

<强>后

let stringAttributes = [NSFontAttributeName: UIFont(name: "Roboto-Regular", size: 18.0)!] 
let attrString = NSAttributedString(string: messageString, attributes: stringAttributes)