开发者

How to rotate viewForHeaderInSection

UITableView has custom header UIView, which contains UILabel. Since table has also section index at right side, I want to center the label in remaining space.

How to rotate viewForHeaderInSection

Problem is how to "center" label in same way, when device is rotated to landscape! I've tried both Interface Builder and code-only and something is always wrong.

Restrictions:

  1. Label is as narrow as possible
  2. Label must not be resized
  3. Label must be always centered inside table width minus section index

One easy way to fix this would be making section header view detached from tableView right side. Tried to do it, failed. Here's some code from viewForHeaderInSection:

CGRect frame = CGRectMake(0, 0, tableView.bounds.size.width - 32, 50.0f);
// MAGIC 32 for SectionIndexTitles

UIView *view = [[[UIView alloc] initWithFrame:frame] autorelease];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.font = [UIFont fontWithName:@"Courier" size:20];
label.text = @"Section title long";
label.textAlignment = UITextAli开发者_如何学编程gnmentCenter;
label.backgroundColor = [UIColor redColor];

CGSize labelSize = [label.text sizeWithFont:label.font
                          constrainedToSize:frame.size
                              lineBreakMode:UILineBreakModeClip];
label.frame = CGRectMake(0, 0, labelSize.width, labelSize.height);
label.center = CGPointMake(frame.size.width/2.0f, kHeaderHeight/2.0f);

label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

Any ideas welcome! Can't even recall how many different ways I have failed :)


Hey, set up as following in the IB: Disable all autoresizing functionalities (no flexible width, height, nor any left, bottom, top, right).

Should do the job :)

To support the magic 32 pixels, try to position your Label as you need it. That means: Position it in the center of your UIView and move it 16 pixels to the left, now don't change the frame programmatically, else the "wonderful" auto-positiong will be manipulated what we don't really want to :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜