2

In my app, I am using a UISegmentedcontrol. Because the label in each of the three segments spans two lines, I need to customize the UISegmentedcontrol. I want to do two things: (1) Increase the height of the UISegmentedcontrol, and (2) Make the text label span two lines

I found the solution to #1 here: iOS: change the height of UISegmentedcontrol and here Change Height of UISegmentedControl and here http://iphonedevsdk.com/forum/iphone-sdk-development/74275-change-height-of-segmented-control.html

I couldn't find out how to make the label inside the UISegmentedcontrol span two lines. Any help would be greatly appreciated!

Cheers, Frank

Community
  • 1
  • 1
Frank
  • 41
  • 5

1 Answers1

8

try this... create a Category for UISegmentedControl ,suppose UISegmentedControl+Multiline

in UISegmentedControl+Multiline.h

#import <UIKit/UIKit.h>

@interface UISegmentedControl (Multiline)

- (void)insertSegmentWithMultilineTitle:(NSString *)title atIndex:(NSUInteger)segment animated:(BOOL)animated;

@end

and in UISegmentedControl+Multiline.m

#import "UISegmentedControl+Multiline.h"

@interface UIView (LayerShot)

- (UIImage *)imageFromLayer;

@end

@implementation UIView (LayerShot)

- (UIImage *)imageFromLayer {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end

@implementation UISegmentedControl (Multiline)

- (void)insertSegmentWithMultilineTitle:(NSString *)title atIndex:(NSUInteger)segment animated:(BOOL)animated {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    [label setTextColor:[self tintColor]];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setFont:[UIFont systemFontOfSize:13]];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setLineBreakMode:NSLineBreakByWordWrapping];
    [label setNumberOfLines:0];

    [label setText:title];
    [label sizeToFit];

    [self insertSegmentWithImage:[label imageFromLayer] atIndex:segment animated:animated];
}
@end

finally import UISegmentedControl+Multiline.h in your class and use as follows

 UISegmentedControl * segmentControl = [[UISegmentedControl alloc]initWithFrame:CGRectMake(3, 66, 314, 30)];

    [segmentControl insertSegmentWithMultilineTitle:@"First\nLine" atIndex:0 animated:YES];
    [segmentControl insertSegmentWithMultilineTitle:@"Second\nLine" atIndex:1 animated:YES];
    [segmentControl insertSegmentWithMultilineTitle:@"Third\nLine" atIndex:2 animated:YES];
    [segmentControl setSelectedSegmentIndex:0];
    [segmentControl addTarget:self action:@selector(segmentControlClicked:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segmentControl];
Ravi
  • 2,441
  • 1
  • 11
  • 30