如何定制iphone中的UISwitch按钮?

如何定制iphone中的UISwitch按钮?,iphone,text,customization,background-color,uiswitch,Iphone,Text,Customization,Background Color,Uiswitch,我用这段代码创建了一个UISwitch UISwitch *switch = [[UISwitch alloc]initWithFrame:CGRectMake(110, 230, 60, 60)]; [window addSubview:switchView]; [switchView release]; 已创建的按钮将是 默认属性为 它包含“打开”和“关闭”状态 关闭按钮为白色,打开按钮为蓝色 我想创建一个自定义的开关,这样开关中的背景色和文本就应该改变。可能吗?请详细解释 提前感谢,

我用这段代码创建了一个UISwitch

UISwitch *switch = [[UISwitch alloc]initWithFrame:CGRectMake(110, 230, 60, 60)];
[window addSubview:switchView];
[switchView release];
已创建的按钮将是

默认属性为

  • 它包含“打开”和“关闭”状态
  • 关闭按钮为白色,打开按钮为蓝色
  • 我想创建一个自定义的开关,这样开关中的背景色和文本就应该改变。可能吗?请详细解释

    提前感谢,


    Rajkanth

    您不能修改UISwitch控件,除非您编写自己的控件

    但到目前为止,最好的方法是使用UISegmentControl并处理其上的事件来切换on.png和off.png图像

    UISegmentedControl* switchView=[[UISegmentedControl alloc] initWithItems:[[[NSMutableArray alloc] initWithObjects:@"On",@"Off",nil] autorelease]];
        [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];
    
        self.navigationItem.titleView=switchView;
    然后像这样编写checkOnOffState方法代码-

    -(IBAction)checkOnOffState:(id)sender{
    
        UISegmentedControl* tempSeg=(UISegmentedControl *)sender;
        if(tempSeg.selectedSegmentIndex==0){
            [tempSeg setImage:[UIImage imageNamed:@"onSelected.png"] forSegmentAtIndex:0];
            [tempSeg setImage:[UIImage imageNamed:@"off.png"] forSegmentAtIndex:1];
        }
        else{
            [tempSeg setImage:[UIImage imageNamed:@"on.png"] forSegmentAtIndex:0];
            [tempSeg setImage:[UIImage imageNamed:@"offSelected.png"] forSegmentAtIndex:1];
        }   
    }
    我使用了这个解决方案::它可以定制UISlider并将最大值设置为1

    您可以更改开关的图像、右/左文本,并将其与唯一的背景颜色一起使用(如果您不想使用图像)


    我所做的唯一更改是关于名称:UI是为Apple classe保留的,所以我自己更改了它。

    onSelected.png图像和on.png图像之间的区别是什么?“选定”位是否为实际旋钮,on/off.png是否为轨迹?我们可以设置的图像大小是否有任何限制?我的图像位于片段的中心,没有利用全部空间。任何帮助都将不胜感激。