1

So what my problem is that my text above my section is too long and gets cut off.

example

Any way to solve this like making it two rows long?

Any help is appreciated

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Cing
  • 806
  • 1
  • 11
  • 29
  • 1
    Respond to the delegate `tableView:viewForHeaderInSection ` https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/#//apple_ref/occ/intfm/UITableViewDelegate/tableView:viewForHeaderInSection: Return a taller view with a multiline label subview – danh Jul 08 '16 at 17:28
  • Possible duplicate of [Customize UITableView header section](http://stackoverflow.com/questions/15611374/customize-uitableview-header-section) – Ishmeet Jul 08 '16 at 17:54

2 Answers2

4

You need to define the heightForHeaderInSection and customize viewForHeaderInSection. You can either fix all header heights at a value big enough for all lines, or calculate the required height for the specific header (as below).

let headerFont:UIFont = UIFont.systemFontOfSize(14);
let headerTexts = ["one line", "two line test123 sadfjklsadf asdjfklasjdflk asdfjklasdjfl asdfjklsadf"];

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 2;
}

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return heightOfHeaderText(headerTexts[section]);
}

func heightOfHeaderText(text:String) -> CGFloat{
    return NSString(string: text).boundingRectWithSize(
        CGSizeMake(self.tableView.frame.size.width, 999),
        options: NSStringDrawingOptions.UsesLineFragmentOrigin,
        attributes: [NSFontAttributeName : headerFont],
        context: nil).size.height;


}

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerLabel:UILabel = UILabel.init(frame: CGRectMake(0, 0, tableView.frame.size.width, self.tableView(tableView, heightForHeaderInSection: section)));
    headerLabel.numberOfLines = 0;
    headerLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping;
    headerLabel.font = headerFont;
    headerLabel.text = headerTexts[section];

    return headerLabel;


}
bradkratky
  • 1,577
  • 1
  • 14
  • 28
1

Make a custom view with a label in it. And use viewForHeaderInSection delegate method to assign text to that label and return this view.

EDIT:

See this link Customize UITableView header section

Community
  • 1
  • 1
Ishmeet
  • 707
  • 6
  • 18