Swift: 在 sizetofit 之后无法获得 header 单元格标签的正确高度

Swift: Cannot get correct height of header cell's label after sizetofit

我已将 sizeToFit() 添加到 UILabel,但是我无法获得无法显示所有文本的正确高度。它只显示“学术、行政、教学和

测试对象:iphone6

编码:

class eventsViewController: UITableViewController {
     var headerName: Array<String> = ["Academic, administrative, teaching and learning support units"]

   override func viewDidLoad() {
       self.tableView = UITableView(frame: self.tableView.frame, style: .Grouped)
       self.view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
       self.tableView.estimatedRowHeight = 102
    }
   override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {


    var headerCell = tableView.dequeueReusableCellWithIdentifier("EventsHeaderCell") as! UITableViewCell!

    if headerCell == nil {
        headerCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "EventsHeaderCell")
    }
    headerCell!.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
    headerCell!.textLabel?.text = headerName[section]
    headerCell!.textLabel?.numberOfLines = 0
    headerCell!.textLabel?.lineBreakMode = .ByWordWrapping
    headerCell!.textLabel?.sizeToFit()
    headerCell!.userInteractionEnabled = false;
    headerCell!.sizeToFit()
    return headerCell!
   }
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return headerName.count
    }

    override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            var headerLabel:UILabel = UILabel()
            headerLabel.text = headerName[section]
            headerLabel.numberOfLines = 0
            headerLabel.lineBreakMode = .ByWordWrapping
            headerLabel.sizeToFit()

            return headerLabel.frame.size.height

        }

}

问题是不间断的长文本导致在 sizeToFit() 之后获得不间断的 UILabel 高度。但是,它表明文本已在 iPhone 6 和 ios 8.

中中断
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    var headerLabel:UILabel = UILabel()
    var newline: CGFloat = 1
    headerLabel.text = headerName[section]
    headerLabel.numberOfLines = 0
    headerLabel.lineBreakMode = .ByWordWrapping
    headerLabel.sizeToFit()

    if self.view.frame.width <= headerLabel.frame.width
    {
        newline = ceil(headerLabel.frame.width/self.view.frame.width)
    }

    let tblHeaderHeight = (headerLabel.frame.size.height * newline) + ios7_8Info.getEventHeaderCellSpacingHeight() as CGFloat
    return tblHeaderHeight
}