简体   繁体   中英

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.

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];

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

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

eg:

[segmentedControl setImage:[UIImage imageNamed:@"segment1.png"] forSegmentAtIndex:0];

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

使用IB进行图像设置

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

结果

Happy xCoding! )

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 在此输入图像描述

在xcode 4.6.3中,界面构建器中有一个选项可以将图像添加到段控件中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM