Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set image to the UISegmentedControl in iPhone?

I am new to iPhone development. I have created UISegmentedControl having 2 segments. I want to display images for each segment instead of title. Here is my code

NSArray *itemArray = [NSArray arrayWithObjects: @"segment1", @"segment2", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(5,100,300,40);
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.selectedSegmentIndex = 1;
[self.view addSubview:segmentedControl];
[segmentedControl release]; 

But instead of displaying the title ,segment1 and segment2 it should be replaced with the images I have.

like image 424
Warrior Avatar asked Jun 08 '10 21:06

Warrior


2 Answers

It is almost exactly what you had, just pass an array of UIImages instead of NSStrings.

NSArray *itemArray = [NSArray arrayWithObjects:
    [UIImage imageNamed:@"segment1.png"],
    [UIImage imageNamed:@"segment2.png"],
    nil];
like image 132
drawnonward Avatar answered Oct 24 '22 17:10

drawnonward


If you want to change the image during runtime, use the following method:

- (void)setImage:(UIImage *)image forSegmentAtIndex:(NSUInteger)segment

e.g.:

[segmentedControl setImage:[UIImage imageNamed:@"segment1.png"] forSegmentAtIndex:0];
like image 30
snibbe Avatar answered Oct 24 '22 19:10

snibbe