将自定义开关添加到iphone视图

将自定义开关添加到iphone视图,iphone,user-interface,custom-controls,Iphone,User Interface,Custom Controls,我正在使用以下代码创建自定义开关: UISegmentedControl* switchView=[[UISegmentedControl alloc] initWithItems:[[NSMutableArray alloc] initWithObjects:@"On",@"Off",nil]]; [switchView setFrame:CGRectMake(20,365,140,28)]; switchView.select

我正在使用以下代码创建自定义开关:

UISegmentedControl* switchView=[[UISegmentedControl alloc] 
                                initWithItems:[[NSMutableArray alloc] initWithObjects:@"On",@"Off",nil]];
[switchView setFrame:CGRectMake(20,365,140,28)];
switchView.selectedSegmentIndex=0;
switchView.segmentedControlStyle=UISegmentedControlStyleBar;
[switchView setImage:[UIImage imageNamed:@"onSelected.png"] forSegmentAtIndex:0];
[switchView setImage:[UIImage imageNamed:@"off.png"] forSegmentAtIndex:1];
[switchView addTarget:self action:@selector(checkOnOffState:) forControlEvents:UIControlEventValueChanged];
我现在想把这个控件添加到我的一个屏幕上(我相信正确的术语是ViewController?)。在Xcode 4.3中我将如何做到这一点

我看了其他几个帖子,没有找到任何有效的。例如,建议使用

[[myVC视图]添加子视图:myView]
并建议

self.navigationItem.titleView=switchView

如果可能的话,你能解释一下为什么这些方法不起作用吗?谢谢。

您需要为您的交换机创建一个类,它是UISegmentControl的子类, 否则,您也可以直接在vc中添加此代码

将此代码添加到其initWithFrame方法中

然后在VC中使用它

-(void)viewDidLoad{
  urCustomSwitch  = [urCustomSwitch alloc] initWithFrame:CGRectMake(20,365,140,28)];
  [self.view addSubview:urCustomSwitch];
}

如果您要创建自定义的可重用类,那么这将符合您的目的

如果在
InterfaceBuilder
(.xib文件)中添加此开关控件,即
UISegmentedControl


这项任务对您来说会容易得多。

谢谢您的回复。我是否应该将此类设置为UITableViewController、UITableViewCell、AppDelegate、CIColor或CIContext的子类。我想我应该让它成为UIView的一个子类,但这不是选项之一。再次感谢。您可以将其设置为
UISegmentControl
的子类,或者
UIView
也是一个选项。这对我不起作用,因为我的自定义开关没有alloc方法。我必须做些什么才能使用它,还是必须以另一种方式实例化它?如果您对任何UIControl或UIView进行子类化,您需要覆盖此方法并在其中编写代码。您的意思是将我的自定义类(UISegmentedControl的子类)添加到InterfaceBuilder中。我可以通过创建.xib文件来实现这一点吗?谢谢