How to set image to the UISegmentedControl in iPhone?

风流意气都作罢 提交于 2019-12-18 11:32:51

问题


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.


回答1:


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



回答2:


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



回答3:


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

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

Happy xCoding! )




回答4:


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




回答5:


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



来源:https://stackoverflow.com/questions/3001313/how-to-set-image-to-the-uisegmentedcontrol-in-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!