18

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Warrior
  • 39,156
  • 44
  • 139
  • 214

5 Answers5

29

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];
drawnonward
  • 53,459
  • 16
  • 107
  • 112
  • 11
    Is it possible to have text and image both on segmented control? – Paresh Masani Nov 10 '11 at 11:02
  • 1
    @AppleDeveloper, nope. – AndrewShmig Mar 31 '14 at 16:27
  • 1
    Although it is possible to set both a label and an image for a segment, a segment should have one or the other, as described in macOS Human Interface Guidelines. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/SegmentedControl/Articles/SegmentedControlCode.html – Jeff Jun 12 '17 at 17:56
24

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];
snibbe
  • 2,715
  • 1
  • 27
  • 34
13

It's simple to do it with Interface Builder (Attributes Inspector tab).

Image setting with IB

Also you can set one segment with image and the other one with text.

Result

Happy xCoding! )

Anton Gaenko
  • 8,929
  • 6
  • 44
  • 39
5

For interface builder user, set "render as" as "original image" rather than default. In my case, it will show after running. It may work. @jcpennypincher enter image description here

Albert Zou
  • 165
  • 2
  • 4
1

In xcode 4.6.3 there is an option in interface builder to add an image to the segment controls.

Nikhil Dinesh
  • 3,359
  • 2
  • 38
  • 41