Pangu
Pangu

Reputation: 3819

How to pad a UITableView section header?

How would you add some padding to a section header in a UITableView cell?

I have this: enter image description here

I have an NSDictionary whose key values contain a string of times. I stored the key values in an NSArray.

I am using titleForHeaderInSection instead of viewForHeaderInSection.

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{   
    return [schedule objectAtIndex:section];
}

However, the section header is aligned all the way to the left. I can pad it to my liking using a UIView for viewForHeaderInSection, but is there any way to do it for the method titleForHeaderInSection?

Upvotes: 6

Views: 3468

Answers (4)

App Dev Guy
App Dev Guy

Reputation: 5536

I think the easiest solution is nesting your label in a view. See below for Swift 2 answer:

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

    // Create the header view
    let headerView =  UIView.init(frame: CGRectMake(0, 0, self.view.frame.size.width, 30))
    headerView.backgroundColor = UIColor.lightGrayColor()

    // Create the Label 
    let label: UILabel? = UILabel(frame: CGRectMake(20, 0, 120, 30))
    label!.textAlignment = .Left
    label!.text = "Your Section Title"

    // Add the label to your headerview 
    headerView.addSubview(label)

    return headerView
}

And presto, you have a header view with an indentation of 20 on your text :-D

Upvotes: 2

Pangu
Pangu

Reputation: 3819

I couldn't easily do it using the titleForHeaderInSection so I decided to use a custom cell with viewForHeaderInSection.

Upvotes: 2

Arben Pnishi
Arben Pnishi

Reputation: 591

Based on the answer shown here: You have heights viewHeader = 30, lblHeadertitle = 20.

At the code:

UILabel *lblHeadertitle = [[UILabel alloc] initWithFrame:CGRectMake(YOUR_LEFT_PADDING, YOUR_TOP_PADDING, 200, 20)];

Set the YOUR_TOP_PADDING=5 because the lblHeadertitle is subview of viewHeader and let it be centered in the viewHeader.

Hope it helps.

Upvotes: 0

Abhishek
Abhishek

Reputation: 1702

better to use tableView:viewForHeaderInSection

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 30;
}

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
      UIView *viewHeader = [UIView.alloc initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
      UILabel *lblHeadertitle = [[UILabel alloc] initWithFrame:CGRectMake(YOUR_LEFT_PADDING, YOUR_TOP_PADDING, 200, 20)];
      //customize lblHeadertitle
      lblHeadertitle.text = [schedule objectAtIndex:section];
      [viewHeader addSubview:lblHeadertitle];

      return viewHeader;
    }

Upvotes: 0

Related Questions