简体   繁体   English

如何在iPhone中将图像设置为UISegmentedControl?

[英]How to set image to the UISegmentedControl in iPhone?

I am new to iPhone development. 我是iPhone开发的新手。 I have created UISegmentedControl having 2 segments. 我创建了UISegmentedControl有2个段。 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. 但是不应该显示标题,segment1和segment2,而应该用我拥有的图像替换它。

It is almost exactly what you had, just pass an array of UIImages instead of NSStrings. 它几乎就是你所拥有的,只是传递一组UIImages而不是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). 使用Interface BuilderAttributes Inspector选项卡)执行此操作非常简单。

使用IB进行图像设置

Also you can set one segment with image and the other one with text. 您还可以使用图像设置一个片段,使用文本设置另一个片段。

结果

Happy xCoding! 快乐的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 @jcpennypincher 在此输入图像描述

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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